New message noarticletext-nopermission that does not include misleading link 'edit...
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @file
5 */
6
7 /**
8 * Class representing a MediaWiki article and history.
9 *
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
13 *
14 */
15 class Article {
16 /**@{{
17 * @private
18 */
19 var $mComment = ''; //!<
20 var $mContent; //!<
21 var $mContentLoaded = false; //!<
22 var $mCounter = -1; //!< Not loaded
23 var $mCurID = -1; //!< Not loaded
24 var $mDataLoaded = false; //!<
25 var $mForUpdate = false; //!<
26 var $mGoodAdjustment = 0; //!<
27 var $mIsRedirect = false; //!<
28 var $mLatest = false; //!<
29 var $mMinorEdit; //!<
30 var $mOldId; //!<
31 var $mPreparedEdit = false; //!< Title object if set
32 var $mRedirectedFrom = null; //!< Title object if set
33 var $mRedirectTarget = null; //!< Title object if set
34 var $mRedirectUrl = false; //!<
35 var $mRevIdFetched = 0; //!<
36 var $mRevision; //!<
37 var $mTimestamp = ''; //!<
38 var $mTitle; //!<
39 var $mTotalAdjustment = 0; //!<
40 var $mTouched = '19700101000000'; //!<
41 var $mUser = -1; //!< Not loaded
42 var $mUserText = ''; //!<
43 var $mParserOptions; //!<
44 var $mParserOutput; //!<
45 /**@}}*/
46
47 /**
48 * Constructor and clear the article
49 * @param $title Reference to a Title object.
50 * @param $oldId Integer revision ID, null to fetch from request, zero for current
51 */
52 public function __construct( Title $title, $oldId = null ) {
53 $this->mTitle =& $title;
54 $this->mOldId = $oldId;
55 }
56
57 /**
58 * Constructor from an article article
59 * @param $id The article ID to load
60 */
61 public static function newFromID( $id ) {
62 $t = Title::newFromID( $id );
63 return $t == null ? null : new Article( $t );
64 }
65
66 /**
67 * Tell the page view functions that this view was redirected
68 * from another page on the wiki.
69 * @param $from Title object.
70 */
71 public function setRedirectedFrom( $from ) {
72 $this->mRedirectedFrom = $from;
73 }
74
75 /**
76 * If this page is a redirect, get its target
77 *
78 * The target will be fetched from the redirect table if possible.
79 * If this page doesn't have an entry there, call insertRedirect()
80 * @return mixed Title object, or null if this page is not a redirect
81 */
82 public function getRedirectTarget() {
83 if( !$this->mTitle || !$this->mTitle->isRedirect() )
84 return null;
85 if( !is_null($this->mRedirectTarget) )
86 return $this->mRedirectTarget;
87 # Query the redirect table
88 $dbr = wfGetDB( DB_SLAVE );
89 $row = $dbr->selectRow( 'redirect',
90 array('rd_namespace', 'rd_title'),
91 array('rd_from' => $this->getID() ),
92 __METHOD__
93 );
94 if( $row ) {
95 return $this->mRedirectTarget = Title::makeTitle($row->rd_namespace, $row->rd_title);
96 }
97 # This page doesn't have an entry in the redirect table
98 return $this->mRedirectTarget = $this->insertRedirect();
99 }
100
101 /**
102 * Insert an entry for this page into the redirect table.
103 *
104 * Don't call this function directly unless you know what you're doing.
105 * @return Title object
106 */
107 public function insertRedirect() {
108 $retval = Title::newFromRedirect( $this->getContent() );
109 if( !$retval ) {
110 return null;
111 }
112 $dbw = wfGetDB( DB_MASTER );
113 $dbw->replace( 'redirect', array('rd_from'),
114 array(
115 'rd_from' => $this->getID(),
116 'rd_namespace' => $retval->getNamespace(),
117 'rd_title' => $retval->getDBkey()
118 ),
119 __METHOD__
120 );
121 return $retval;
122 }
123
124 /**
125 * Get the Title object this page redirects to
126 *
127 * @return mixed false, Title of in-wiki target, or string with URL
128 */
129 public function followRedirect() {
130 $text = $this->getContent();
131 return $this->followRedirectText( $text );
132 }
133
134 /**
135 * Get the Title object this text redirects to
136 *
137 * @return mixed false, Title of in-wiki target, or string with URL
138 */
139 public function followRedirectText( $text ) {
140 $rt = Title::newFromRedirectRecurse( $text ); // recurse through to only get the final target
141 # process if title object is valid and not special:userlogout
142 if( $rt ) {
143 if( $rt->getInterwiki() != '' ) {
144 if( $rt->isLocal() ) {
145 // Offsite wikis need an HTTP redirect.
146 //
147 // This can be hard to reverse and may produce loops,
148 // so they may be disabled in the site configuration.
149 $source = $this->mTitle->getFullURL( 'redirect=no' );
150 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
151 }
152 } else {
153 if( $rt->getNamespace() == NS_SPECIAL ) {
154 // Gotta handle redirects to special pages differently:
155 // Fill the HTTP response "Location" header and ignore
156 // the rest of the page we're on.
157 //
158 // This can be hard to reverse, so they may be disabled.
159 if( $rt->isSpecial( 'Userlogout' ) ) {
160 // rolleyes
161 } else {
162 return $rt->getFullURL();
163 }
164 }
165 return $rt;
166 }
167 }
168 // No or invalid redirect
169 return false;
170 }
171
172 /**
173 * get the title object of the article
174 */
175 public function getTitle() {
176 return $this->mTitle;
177 }
178
179 /**
180 * Clear the object
181 * @private
182 */
183 public function clear() {
184 $this->mDataLoaded = false;
185 $this->mContentLoaded = false;
186
187 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
188 $this->mRedirectedFrom = null; # Title object if set
189 $this->mRedirectTarget = null; # Title object if set
190 $this->mUserText =
191 $this->mTimestamp = $this->mComment = '';
192 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
193 $this->mTouched = '19700101000000';
194 $this->mForUpdate = false;
195 $this->mIsRedirect = false;
196 $this->mRevIdFetched = 0;
197 $this->mRedirectUrl = false;
198 $this->mLatest = false;
199 $this->mPreparedEdit = false;
200 }
201
202 /**
203 * Note that getContent/loadContent do not follow redirects anymore.
204 * If you need to fetch redirectable content easily, try
205 * the shortcut in Article::followContent()
206 *
207 * @return Return the text of this revision
208 */
209 public function getContent() {
210 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
211 wfProfileIn( __METHOD__ );
212 if( $this->getID() === 0 ) {
213 # If this is a MediaWiki:x message, then load the messages
214 # and return the message value for x.
215 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
216 # If this is a system message, get the default text.
217 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle->getText() ) );
218 $wgMessageCache->loadAllMessages( $lang );
219 $text = wfMsgGetKey( $message, false, $lang, false );
220 if( wfEmptyMsg( $message, $text ) )
221 $text = '';
222 } else {
223 $text = wfMsgExt( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon', 'parsemag' );
224 }
225 wfProfileOut( __METHOD__ );
226 return $text;
227 } else {
228 $this->loadContent();
229 wfProfileOut( __METHOD__ );
230 return $this->mContent;
231 }
232 }
233
234 /**
235 * Get the text of the current revision. No side-effects...
236 *
237 * @return Return the text of the current revision
238 */
239 public function getRawText() {
240 // Check process cache for current revision
241 if( $this->mContentLoaded && $this->mOldId == 0 ) {
242 return $this->mContent;
243 }
244 $rev = Revision::newFromTitle( $this->mTitle );
245 $text = $rev ? $rev->getRawText() : false;
246 return $text;
247 }
248
249 /**
250 * This function returns the text of a section, specified by a number ($section).
251 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
252 * the first section before any such heading (section 0).
253 *
254 * If a section contains subsections, these are also returned.
255 *
256 * @param $text String: text to look in
257 * @param $section Integer: section number
258 * @return string text of the requested section
259 * @deprecated
260 */
261 public function getSection( $text, $section ) {
262 global $wgParser;
263 return $wgParser->getSection( $text, $section );
264 }
265
266 /**
267 * Get the text that needs to be saved in order to undo all revisions
268 * between $undo and $undoafter. Revisions must belong to the same page,
269 * must exist and must not be deleted
270 * @param $undo Revision
271 * @param $undoafter Revision Must be an earlier revision than $undo
272 * @return mixed string on success, false on failure
273 */
274 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
275 $undo_text = $undo->getText();
276 $undoafter_text = $undoafter->getText();
277 $cur_text = $this->getContent();
278 if ( $cur_text == $undo_text ) {
279 # No use doing a merge if it's just a straight revert.
280 return $undoafter_text;
281 }
282 $undone_text = '';
283 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) )
284 return false;
285 return $undone_text;
286 }
287
288 /**
289 * @return int The oldid of the article that is to be shown, 0 for the
290 * current revision
291 */
292 public function getOldID() {
293 if( is_null( $this->mOldId ) ) {
294 $this->mOldId = $this->getOldIDFromRequest();
295 }
296 return $this->mOldId;
297 }
298
299 /**
300 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
301 *
302 * @return int The old id for the request
303 */
304 public function getOldIDFromRequest() {
305 global $wgRequest;
306 $this->mRedirectUrl = false;
307 $oldid = $wgRequest->getVal( 'oldid' );
308 if( isset( $oldid ) ) {
309 $oldid = intval( $oldid );
310 if( $wgRequest->getVal( 'direction' ) == 'next' ) {
311 $nextid = $this->mTitle->getNextRevisionID( $oldid );
312 if( $nextid ) {
313 $oldid = $nextid;
314 } else {
315 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
316 }
317 } elseif( $wgRequest->getVal( 'direction' ) == 'prev' ) {
318 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
319 if( $previd ) {
320 $oldid = $previd;
321 }
322 }
323 }
324 if( !$oldid ) {
325 $oldid = 0;
326 }
327 return $oldid;
328 }
329
330 /**
331 * Load the revision (including text) into this object
332 */
333 function loadContent() {
334 if( $this->mContentLoaded ) return;
335 wfProfileIn( __METHOD__ );
336 # Query variables :P
337 $oldid = $this->getOldID();
338 # Pre-fill content with error message so that if something
339 # fails we'll have something telling us what we intended.
340 $this->mOldId = $oldid;
341 $this->fetchContent( $oldid );
342 wfProfileOut( __METHOD__ );
343 }
344
345
346 /**
347 * Fetch a page record with the given conditions
348 * @param $dbr Database object
349 * @param $conditions Array
350 */
351 protected function pageData( $dbr, $conditions ) {
352 $fields = array(
353 'page_id',
354 'page_namespace',
355 'page_title',
356 'page_restrictions',
357 'page_counter',
358 'page_is_redirect',
359 'page_is_new',
360 'page_random',
361 'page_touched',
362 'page_latest',
363 'page_len',
364 );
365 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
366 $row = $dbr->selectRow(
367 'page',
368 $fields,
369 $conditions,
370 __METHOD__
371 );
372 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
373 return $row ;
374 }
375
376 /**
377 * @param $dbr Database object
378 * @param $title Title object
379 */
380 public function pageDataFromTitle( $dbr, $title ) {
381 return $this->pageData( $dbr, array(
382 'page_namespace' => $title->getNamespace(),
383 'page_title' => $title->getDBkey() ) );
384 }
385
386 /**
387 * @param $dbr Database
388 * @param $id Integer
389 */
390 protected function pageDataFromId( $dbr, $id ) {
391 return $this->pageData( $dbr, array( 'page_id' => $id ) );
392 }
393
394 /**
395 * Set the general counter, title etc data loaded from
396 * some source.
397 *
398 * @param $data Database row object or "fromdb"
399 */
400 public function loadPageData( $data = 'fromdb' ) {
401 if( $data === 'fromdb' ) {
402 $dbr = wfGetDB( DB_MASTER );
403 $data = $this->pageDataFromId( $dbr, $this->getId() );
404 }
405
406 $lc = LinkCache::singleton();
407 if( $data ) {
408 $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect );
409
410 $this->mTitle->mArticleID = intval( $data->page_id );
411
412 # Old-fashioned restrictions
413 $this->mTitle->loadRestrictions( $data->page_restrictions );
414
415 $this->mCounter = intval( $data->page_counter );
416 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
417 $this->mIsRedirect = intval( $data->page_is_redirect );
418 $this->mLatest = intval( $data->page_latest );
419 } else {
420 if( is_object( $this->mTitle ) ) {
421 $lc->addBadLinkObj( $this->mTitle );
422 }
423 $this->mTitle->mArticleID = 0;
424 }
425
426 $this->mDataLoaded = true;
427 }
428
429 /**
430 * Get text of an article from database
431 * Does *NOT* follow redirects.
432 * @param $oldid Int: 0 for whatever the latest revision is
433 * @return string
434 */
435 function fetchContent( $oldid = 0 ) {
436 if( $this->mContentLoaded ) {
437 return $this->mContent;
438 }
439
440 $dbr = wfGetDB( DB_MASTER );
441
442 # Pre-fill content with error message so that if something
443 # fails we'll have something telling us what we intended.
444 $t = $this->mTitle->getPrefixedText();
445 $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
446 $this->mContent = wfMsg( 'missing-article', $t, $d ) ;
447
448 if( $oldid ) {
449 $revision = Revision::newFromId( $oldid );
450 if( is_null( $revision ) ) {
451 wfDebug( __METHOD__." failed to retrieve specified revision, id $oldid\n" );
452 return false;
453 }
454 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
455 if( !$data ) {
456 wfDebug( __METHOD__." failed to get page data linked to revision id $oldid\n" );
457 return false;
458 }
459 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
460 $this->loadPageData( $data );
461 } else {
462 if( !$this->mDataLoaded ) {
463 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
464 if( !$data ) {
465 wfDebug( __METHOD__." failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
466 return false;
467 }
468 $this->loadPageData( $data );
469 }
470 $revision = Revision::newFromId( $this->mLatest );
471 if( is_null( $revision ) ) {
472 wfDebug( __METHOD__." failed to retrieve current page, rev_id {$this->mLatest}\n" );
473 return false;
474 }
475 }
476
477 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
478 // We should instead work with the Revision object when we need it...
479 $this->mContent = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed
480
481 $this->mUser = $revision->getUser();
482 $this->mUserText = $revision->getUserText();
483 $this->mComment = $revision->getComment();
484 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
485
486 $this->mRevIdFetched = $revision->getId();
487 $this->mContentLoaded = true;
488 $this->mRevision =& $revision;
489
490 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
491
492 return $this->mContent;
493 }
494
495 /**
496 * Read/write accessor to select FOR UPDATE
497 *
498 * @param $x Mixed: FIXME
499 */
500 public function forUpdate( $x = NULL ) {
501 return wfSetVar( $this->mForUpdate, $x );
502 }
503
504 /**
505 * Get the database which should be used for reads
506 *
507 * @return Database
508 * @deprecated - just call wfGetDB( DB_MASTER ) instead
509 */
510 function getDB() {
511 wfDeprecated( __METHOD__ );
512 return wfGetDB( DB_MASTER );
513 }
514
515 /**
516 * Get options for all SELECT statements
517 *
518 * @param $options Array: an optional options array which'll be appended to
519 * the default
520 * @return Array: options
521 */
522 protected function getSelectOptions( $options = '' ) {
523 if( $this->mForUpdate ) {
524 if( is_array( $options ) ) {
525 $options[] = 'FOR UPDATE';
526 } else {
527 $options = 'FOR UPDATE';
528 }
529 }
530 return $options;
531 }
532
533 /**
534 * @return int Page ID
535 */
536 public function getID() {
537 if( $this->mTitle ) {
538 return $this->mTitle->getArticleID();
539 } else {
540 return 0;
541 }
542 }
543
544 /**
545 * @return bool Whether or not the page exists in the database
546 */
547 public function exists() {
548 return $this->getId() > 0;
549 }
550
551 /**
552 * Check if this page is something we're going to be showing
553 * some sort of sensible content for. If we return false, page
554 * views (plain action=view) will return an HTTP 404 response,
555 * so spiders and robots can know they're following a bad link.
556 *
557 * @return bool
558 */
559 public function hasViewableContent() {
560 return $this->exists() || $this->mTitle->isAlwaysKnown();
561 }
562
563 /**
564 * @return int The view count for the page
565 */
566 public function getCount() {
567 if( -1 == $this->mCounter ) {
568 $id = $this->getID();
569 if( $id == 0 ) {
570 $this->mCounter = 0;
571 } else {
572 $dbr = wfGetDB( DB_SLAVE );
573 $this->mCounter = $dbr->selectField( 'page',
574 'page_counter',
575 array( 'page_id' => $id ),
576 __METHOD__,
577 $this->getSelectOptions()
578 );
579 }
580 }
581 return $this->mCounter;
582 }
583
584 /**
585 * Determine whether a page would be suitable for being counted as an
586 * article in the site_stats table based on the title & its content
587 *
588 * @param $text String: text to analyze
589 * @return bool
590 */
591 public function isCountable( $text ) {
592 global $wgUseCommaCount;
593
594 $token = $wgUseCommaCount ? ',' : '[[';
595 return $this->mTitle->isContentPage() && !$this->isRedirect($text) && in_string($token,$text);
596 }
597
598 /**
599 * Tests if the article text represents a redirect
600 *
601 * @param $text String: FIXME
602 * @return bool
603 */
604 public function isRedirect( $text = false ) {
605 if( $text === false ) {
606 if( $this->mDataLoaded ) {
607 return $this->mIsRedirect;
608 }
609 // Apparently loadPageData was never called
610 $this->loadContent();
611 $titleObj = Title::newFromRedirectRecurse( $this->fetchContent() );
612 } else {
613 $titleObj = Title::newFromRedirect( $text );
614 }
615 return $titleObj !== NULL;
616 }
617
618 /**
619 * Returns true if the currently-referenced revision is the current edit
620 * to this page (and it exists).
621 * @return bool
622 */
623 public function isCurrent() {
624 # If no oldid, this is the current version.
625 if( $this->getOldID() == 0 ) {
626 return true;
627 }
628 return $this->exists() && isset($this->mRevision) && $this->mRevision->isCurrent();
629 }
630
631 /**
632 * Loads everything except the text
633 * This isn't necessary for all uses, so it's only done if needed.
634 */
635 protected function loadLastEdit() {
636 if( -1 != $this->mUser )
637 return;
638
639 # New or non-existent articles have no user information
640 $id = $this->getID();
641 if( 0 == $id ) return;
642
643 $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
644 if( !is_null( $this->mLastRevision ) ) {
645 $this->mUser = $this->mLastRevision->getUser();
646 $this->mUserText = $this->mLastRevision->getUserText();
647 $this->mTimestamp = $this->mLastRevision->getTimestamp();
648 $this->mComment = $this->mLastRevision->getComment();
649 $this->mMinorEdit = $this->mLastRevision->isMinor();
650 $this->mRevIdFetched = $this->mLastRevision->getId();
651 }
652 }
653
654 public function getTimestamp() {
655 // Check if the field has been filled by ParserCache::get()
656 if( !$this->mTimestamp ) {
657 $this->loadLastEdit();
658 }
659 return wfTimestamp(TS_MW, $this->mTimestamp);
660 }
661
662 public function getUser() {
663 $this->loadLastEdit();
664 return $this->mUser;
665 }
666
667 public function getUserText() {
668 $this->loadLastEdit();
669 return $this->mUserText;
670 }
671
672 public function getComment() {
673 $this->loadLastEdit();
674 return $this->mComment;
675 }
676
677 public function getMinorEdit() {
678 $this->loadLastEdit();
679 return $this->mMinorEdit;
680 }
681
682 /* Use this to fetch the rev ID used on page views */
683 public function getRevIdFetched() {
684 $this->loadLastEdit();
685 return $this->mRevIdFetched;
686 }
687
688 /**
689 * @param $limit Integer: default 0.
690 * @param $offset Integer: default 0.
691 */
692 public function getContributors($limit = 0, $offset = 0) {
693 # XXX: this is expensive; cache this info somewhere.
694
695 $contribs = array();
696 $dbr = wfGetDB( DB_SLAVE );
697 $revTable = $dbr->tableName( 'revision' );
698 $userTable = $dbr->tableName( 'user' );
699 $user = $this->getUser();
700 $pageId = $this->getId();
701
702 $deletedBit = $dbr->bitAnd('rev_deleted', Revision::DELETED_USER); // username hidden?
703
704 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
705 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
706 WHERE rev_page = $pageId
707 AND rev_user != $user
708 AND $deletedBit = 0
709 GROUP BY rev_user, rev_user_text, user_real_name
710 ORDER BY timestamp DESC";
711
712 if($limit > 0)
713 $sql = $dbr->limitResult($sql, $limit, $offset);
714
715 $sql .= ' '. $this->getSelectOptions();
716
717 $res = $dbr->query($sql, __METHOD__ );
718
719 return new UserArrayFromResult( $res );
720 }
721
722 /**
723 * This is the default action of the index.php entry point: just view the
724 * page of the given title.
725 */
726 public function view() {
727 global $wgUser, $wgOut, $wgRequest, $wgContLang;
728 global $wgEnableParserCache, $wgStylePath, $wgParser;
729 global $wgUseTrackbacks;
730
731 wfProfileIn( __METHOD__ );
732
733 # Get variables from query string
734 $oldid = $this->getOldID();
735 $parserCache = ParserCache::singleton();
736
737 $parserOptions = clone $this->getParserOptions();
738 # Render printable version, use printable version cache
739 if ( $wgOut->isPrintable() ) {
740 $parserOptions->setIsPrintable( true );
741 }
742
743 # Try client and file cache
744 if( $oldid === 0 && $this->checkTouched() ) {
745 global $wgUseETag;
746 if( $wgUseETag ) {
747 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
748 }
749 # Is is client cached?
750 if( $wgOut->checkLastModified( $this->getTouched() ) ) {
751 wfDebug( __METHOD__.": done 304\n" );
752 wfProfileOut( __METHOD__ );
753 return;
754 # Try file cache
755 } else if( $this->tryFileCache() ) {
756 wfDebug( __METHOD__.": done file cache\n" );
757 # tell wgOut that output is taken care of
758 $wgOut->disable();
759 $this->viewUpdates();
760 wfProfileOut( __METHOD__ );
761 return;
762 }
763 }
764
765 $sk = $wgUser->getSkin();
766
767 # getOldID may want us to redirect somewhere else
768 if( $this->mRedirectUrl ) {
769 $wgOut->redirect( $this->mRedirectUrl );
770 wfDebug( __METHOD__.": redirecting due to oldid\n" );
771 wfProfileOut( __METHOD__ );
772 return;
773 }
774
775 $wgOut->setArticleFlag( true );
776 # Set page title (may be overridden by DISPLAYTITLE)
777 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
778
779 # If we got diff in the query, we want to see a diff page instead of the article.
780 if( !is_null( $wgRequest->getVal( 'diff' ) ) ) {
781 wfDebug( __METHOD__.": showing diff page\n" );
782 $this->showDiffPage();
783 wfProfileOut( __METHOD__ );
784 return;
785 }
786
787 # Should the parser cache be used?
788 $useParserCache = $this->useParserCache( $oldid );
789 wfDebug( 'Article::view using parser cache: ' . ($useParserCache ? 'yes' : 'no' ) . "\n" );
790 if( $wgUser->getOption( 'stubthreshold' ) ) {
791 wfIncrStats( 'pcache_miss_stub' );
792 }
793
794 # For the main page, overwrite the <title> element with the con-
795 # tents of 'pagetitle-view-mainpage' instead of the default (if
796 # that's not empty).
797 if( $this->mTitle->equals( Title::newMainPage() )
798 && wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' )
799 {
800 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
801 }
802
803 $wasRedirected = $this->showRedirectedFromHeader();
804 $this->showNamespaceHeader();
805
806 # Iterate through the possible ways of constructing the output text.
807 # Keep going until $outputDone is set, or we run out of things to do.
808 $pass = 0;
809 $outputDone = false;
810 while( !$outputDone && ++$pass ){
811 switch( $pass ){
812 case 1:
813 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
814 break;
815
816 case 2:
817 # Try the parser cache
818 if( $useParserCache ) {
819 $this->mParserOutput = $parserCache->get( $this, $parserOptions );
820 if ( $this->mParserOutput !== false ) {
821 wfDebug( __METHOD__.": showing parser cache contents\n" );
822 $wgOut->addParserOutput( $this->mParserOutput );
823 # Ensure that UI elements requiring revision ID have
824 # the correct version information.
825 $wgOut->setRevisionId( $this->mLatest );
826 $outputDone = true;
827 }
828 }
829 break;
830
831 case 3:
832 $text = $this->getContent();
833 if( $text === false || $this->getID() == 0 ) {
834 wfDebug( __METHOD__.": showing missing article\n" );
835 $this->showMissingArticle();
836 wfProfileOut( __METHOD__ );
837 return;
838 }
839
840 # Another whitelist check in case oldid is altering the title
841 if( !$this->mTitle->userCanRead() ) {
842 wfDebug( __METHOD__.": denied on secondary read check\n" );
843 $wgOut->loginToUse();
844 $wgOut->output();
845 $wgOut->disable();
846 wfProfileOut( __METHOD__ );
847 return;
848 }
849
850 # Are we looking at an old revision
851 if( $oldid && !is_null( $this->mRevision ) ) {
852 $this->setOldSubtitle( $oldid );
853 if ( !$this->showDeletedRevisionHeader() ) {
854 wfDebug( __METHOD__.": cannot view deleted revision\n" );
855 wfProfileOut( __METHOD__ );
856 return;
857 }
858 # If this "old" version is the current, then try the parser cache...
859 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
860 $this->mParserOutput = $parserCache->get( $this, $parserOptions );
861 if ( $this->mParserOutput ) {
862 wfDebug( __METHOD__.": showing parser cache for current rev permalink\n" );
863 $wgOut->addParserOutput( $this->mParserOutput );
864 $wgOut->setRevisionId( $this->mLatest );
865 $this->showViewFooter();
866 $this->viewUpdates();
867 wfProfileOut( __METHOD__ );
868 return;
869 }
870 }
871 }
872
873 # Ensure that UI elements requiring revision ID have
874 # the correct version information.
875 $wgOut->setRevisionId( $this->getRevIdFetched() );
876
877 # Pages containing custom CSS or JavaScript get special treatment
878 if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
879 wfDebug( __METHOD__.": showing CSS/JS source\n" );
880 $this->showCssOrJsPage();
881 $outputDone = true;
882 } else if( $rt = Title::newFromRedirectArray( $text ) ) {
883 wfDebug( __METHOD__.": showing redirect=no page\n" );
884 # Viewing a redirect page (e.g. with parameter redirect=no)
885 # Don't append the subtitle if this was an old revision
886 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
887 # Parse just to get categories, displaytitle, etc.
888 $this->mParserOutput = $wgParser->parse( $text, $this->mTitle, $parserOptions );
889 $wgOut->addParserOutputNoText( $this->mParserOutput );
890 $outputDone = true;
891 }
892 break;
893
894 case 4:
895 # Run the parse, protected by a pool counter
896 wfDebug( __METHOD__.": doing uncached parse\n" );
897 $key = $parserCache->getKey( $this, $parserOptions );
898 $poolCounter = PoolCounter::factory( 'Article::view', $key );
899 $dirtyCallback = $useParserCache ? array( $this, 'tryDirtyCache' ) : false;
900 $status = $poolCounter->executeProtected( array( $this, 'doViewParse' ), $dirtyCallback );
901
902 if ( !$status->isOK() ) {
903 # Connection or timeout error
904 $this->showPoolError( $status );
905 wfProfileOut( __METHOD__ );
906 return;
907 } else {
908 $outputDone = true;
909 }
910 break;
911
912 # Should be unreachable, but just in case...
913 default:
914 break 2;
915 }
916 }
917
918 # Now that we've filled $this->mParserOutput, we know whether
919 # there are any __NOINDEX__ tags on the page
920 $policy = $this->getRobotPolicy( 'view' );
921 $wgOut->setIndexPolicy( $policy['index'] );
922 $wgOut->setFollowPolicy( $policy['follow'] );
923
924 $this->showViewFooter();
925 $this->viewUpdates();
926 wfProfileOut( __METHOD__ );
927 }
928
929 /**
930 * Show a diff page according to current request variables. For use within
931 * Article::view() only, other callers should use the DifferenceEngine class.
932 */
933 public function showDiffPage() {
934 global $wgOut, $wgRequest, $wgUser;
935
936 $diff = $wgRequest->getVal( 'diff' );
937 $rcid = $wgRequest->getVal( 'rcid' );
938 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
939 $purge = $wgRequest->getVal( 'action' ) == 'purge';
940 $htmldiff = $wgRequest->getBool( 'htmldiff' );
941 $unhide = $wgRequest->getInt('unhide') == 1;
942 $oldid = $this->getOldID();
943
944 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $htmldiff, $unhide );
945 // DifferenceEngine directly fetched the revision:
946 $this->mRevIdFetched = $de->mNewid;
947 $de->showDiffPage( $diffOnly );
948
949 // Needed to get the page's current revision
950 $this->loadPageData();
951 if( $diff == 0 || $diff == $this->mLatest ) {
952 # Run view updates for current revision only
953 $this->viewUpdates();
954 }
955 }
956
957 /**
958 * Show a page view for a page formatted as CSS or JavaScript. To be called by
959 * Article::view() only.
960 *
961 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
962 * page views.
963 */
964 public function showCssOrJsPage() {
965 global $wgOut;
966 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
967 // Give hooks a chance to customise the output
968 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
969 // Wrap the whole lot in a <pre> and don't parse
970 $m = array();
971 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
972 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
973 $wgOut->addHTML( htmlspecialchars( $this->mContent ) );
974 $wgOut->addHTML( "\n</pre>\n" );
975 }
976 }
977
978 /**
979 * Get the robot policy to be used for the current action=view request.
980 * @return String the policy that should be set
981 * @deprecated use getRobotPolicy() instead, which returns an associative
982 * array
983 */
984 public function getRobotPolicyForView() {
985 wfDeprecated( __FUNC__ );
986 $policy = $this->getRobotPolicy( 'view' );
987 return $policy['index'] . ',' . $policy['follow'];
988 }
989
990 /**
991 * Get the robot policy to be used for the current view
992 * @param $action String the action= GET parameter
993 * @return Array the policy that should be set
994 * TODO: actions other than 'view'
995 */
996 public function getRobotPolicy( $action ){
997
998 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
999 global $wgDefaultRobotPolicy, $wgRequest;
1000
1001 $ns = $this->mTitle->getNamespace();
1002 if( $ns == NS_USER || $ns == NS_USER_TALK ) {
1003 # Don't index user and user talk pages for blocked users (bug 11443)
1004 if( !$this->mTitle->isSubpage() ) {
1005 $block = new Block();
1006 if( $block->load( $this->mTitle->getText() ) ) {
1007 return array( 'index' => 'noindex',
1008 'follow' => 'nofollow' );
1009 }
1010 }
1011 }
1012
1013 if( $this->getID() === 0 || $this->getOldID() ) {
1014 # Non-articles (special pages etc), and old revisions
1015 return array( 'index' => 'noindex',
1016 'follow' => 'nofollow' );
1017 } elseif( $wgOut->isPrintable() ) {
1018 # Discourage indexing of printable versions, but encourage following
1019 return array( 'index' => 'noindex',
1020 'follow' => 'follow' );
1021 } elseif( $wgRequest->getInt('curid') ) {
1022 # For ?curid=x urls, disallow indexing
1023 return array( 'index' => 'noindex',
1024 'follow' => 'follow' );
1025 }
1026
1027 # Otherwise, construct the policy based on the various config variables.
1028 $policy = self::formatRobotPolicy( $wgDefaultRobotPolicy );
1029
1030 if( isset( $wgNamespaceRobotPolicies[$ns] ) ){
1031 # Honour customised robot policies for this namespace
1032 $policy = array_merge( $policy,
1033 self::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] ) );
1034 }
1035 if( $this->mTitle->canUseNoindex() && is_object( $this->mParserOutput ) && $this->mParserOutput->getIndexPolicy() ){
1036 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1037 # a final sanity check that we have really got the parser output.
1038 $policy = array_merge( $policy,
1039 array( 'index' => $this->mParserOutput->getIndexPolicy() ) );
1040 }
1041
1042 if( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ){
1043 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1044 $policy = array_merge( $policy,
1045 self::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) );
1046 }
1047
1048 return $policy;
1049
1050 }
1051
1052 /**
1053 * Converts a String robot policy into an associative array, to allow
1054 * merging of several policies using array_merge().
1055 * @param $policy Mixed, returns empty array on null/false/'', transparent
1056 * to already-converted arrays, converts String.
1057 * @return associative Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1058 */
1059 public static function formatRobotPolicy( $policy ){
1060 if( is_array( $policy ) ){
1061 return $policy;
1062 } elseif( !$policy ){
1063 return array();
1064 }
1065
1066 $policy = explode( ',', $policy );
1067 $policy = array_map( 'trim', $policy );
1068
1069 $arr = array();
1070 foreach( $policy as $var ){
1071 if( in_array( $var, array('index','noindex') ) ){
1072 $arr['index'] = $var;
1073 } elseif( in_array( $var, array('follow','nofollow') ) ){
1074 $arr['follow'] = $var;
1075 }
1076 }
1077 return $arr;
1078 }
1079
1080 /**
1081 * If this request is a redirect view, send "redirected from" subtitle to
1082 * $wgOut. Returns true if the header was needed, false if this is not a
1083 * redirect view. Handles both local and remote redirects.
1084 */
1085 public function showRedirectedFromHeader() {
1086 global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
1087
1088 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1089 $sk = $wgUser->getSkin();
1090 if( isset( $this->mRedirectedFrom ) ) {
1091 // This is an internally redirected page view.
1092 // We'll need a backlink to the source page for navigation.
1093 if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1094 $redir = $sk->link(
1095 $this->mRedirectedFrom,
1096 null,
1097 array(),
1098 array( 'redirect' => 'no' ),
1099 array( 'known', 'noclasses' )
1100 );
1101 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1102 $wgOut->setSubtitle( $s );
1103
1104 // Set the fragment if one was specified in the redirect
1105 if( strval( $this->mTitle->getFragment() ) != '' ) {
1106 $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
1107 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1108 }
1109
1110 // Add a <link rel="canonical"> tag
1111 $wgOut->addLink( array( 'rel' => 'canonical',
1112 'href' => $this->mTitle->getLocalURL() )
1113 );
1114 return true;
1115 }
1116 } elseif( $rdfrom ) {
1117 // This is an externally redirected view, from some other wiki.
1118 // If it was reported from a trusted site, supply a backlink.
1119 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1120 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
1121 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1122 $wgOut->setSubtitle( $s );
1123 return true;
1124 }
1125 }
1126 return false;
1127 }
1128
1129 /**
1130 * Show a header specific to the namespace currently being viewed, like
1131 * [[MediaWiki:Talkpagetext]]. For Article::view().
1132 */
1133 public function showNamespaceHeader() {
1134 global $wgOut;
1135 if( $this->mTitle->isTalkPage() ) {
1136 $msg = wfMsgNoTrans( 'talkpageheader' );
1137 if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
1138 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1</div>", array( 'talkpageheader' ) );
1139 }
1140 }
1141 }
1142
1143 /**
1144 * Show the footer section of an ordinary page view
1145 */
1146 public function showViewFooter() {
1147 global $wgOut, $wgUseTrackbacks, $wgRequest;
1148 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1149 if( $this->mTitle->getNamespace() == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
1150 $wgOut->addWikiMsg('anontalkpagetext');
1151 }
1152
1153 # If we have been passed an &rcid= parameter, we want to give the user a
1154 # chance to mark this new article as patrolled.
1155 $this->showPatrolFooter();
1156
1157 # Trackbacks
1158 if( $wgUseTrackbacks ) {
1159 $this->addTrackbacks();
1160 }
1161 }
1162
1163 /**
1164 * If patrol is possible, output a patrol UI box. This is called from the
1165 * footer section of ordinary page views. If patrol is not possible or not
1166 * desired, does nothing.
1167 */
1168 public function showPatrolFooter() {
1169 global $wgOut, $wgRequest, $wgUser;
1170 $rcid = $wgRequest->getVal( 'rcid' );
1171
1172 if( !$rcid || !$this->mTitle->exists() || !$this->mTitle->quickUserCan( 'patrol' ) ) {
1173 return;
1174 }
1175
1176 $sk = $wgUser->getSkin();
1177
1178 $wgOut->addHTML(
1179 "<div class='patrollink'>" .
1180 wfMsgHtml(
1181 'markaspatrolledlink',
1182 $sk->link(
1183 $this->mTitle,
1184 wfMsgHtml( 'markaspatrolledtext' ),
1185 array(),
1186 array(
1187 'action' => 'markpatrolled',
1188 'rcid' => $rcid
1189 ),
1190 array( 'known', 'noclasses' )
1191 )
1192 ) .
1193 '</div>'
1194 );
1195 }
1196
1197 /**
1198 * Show the error text for a missing article. For articles in the MediaWiki
1199 * namespace, show the default message text. To be called from Article::view().
1200 */
1201 public function showMissingArticle() {
1202 global $wgOut, $wgRequest;
1203 # Show delete and move logs
1204 $this->showLogs();
1205
1206 # Show error message
1207 $oldid = $this->getOldID();
1208 if( $oldid ) {
1209 $text = wfMsgNoTrans( 'missing-article',
1210 $this->mTitle->getPrefixedText(),
1211 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1212 } elseif ( $this->mTitle->getNamespace() === NS_MEDIAWIKI ) {
1213 // Use the default message text
1214 $text = $this->getContent();
1215 } else {
1216 if ( $this->mTitle->userCan( 'edit' ) )
1217 $text = wfMsgNoTrans( 'noarticletext' );
1218 else
1219 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1220 }
1221 $text = "<div class='noarticletext'>\n$text\n</div>";
1222 if( !$this->hasViewableContent() ) {
1223 // If there's no backing content, send a 404 Not Found
1224 // for better machine handling of broken links.
1225 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
1226 }
1227 $wgOut->addWikiText( $text );
1228 }
1229
1230 /**
1231 * If the revision requested for view is deleted, check permissions.
1232 * Send either an error message or a warning header to $wgOut.
1233 * Returns true if the view is allowed, false if not.
1234 */
1235 public function showDeletedRevisionHeader() {
1236 global $wgOut, $wgRequest;
1237 if( !$this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1238 // Not deleted
1239 return true;
1240 }
1241 // If the user is not allowed to see it...
1242 if( !$this->mRevision->userCan(Revision::DELETED_TEXT) ) {
1243 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1244 'rev-deleted-text-permission' );
1245 return false;
1246 // If the user needs to confirm that they want to see it...
1247 } else if( $wgRequest->getInt('unhide') != 1 ) {
1248 # Give explanation and add a link to view the revision...
1249 $oldid = intval( $this->getOldID() );
1250 $link = $this->mTitle->getFullUrl( "oldid={$oldid}&unhide=1" );
1251 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1252 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1253 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1254 array($msg,$link) );
1255 return false;
1256 // We are allowed to see...
1257 } else {
1258 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1259 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1260 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", $msg );
1261 return true;
1262 }
1263 }
1264
1265 /**
1266 * Show an excerpt from the deletion and move logs. To be called from the
1267 * header section on page views of missing pages.
1268 */
1269 public function showLogs() {
1270 global $wgUser, $wgOut;
1271 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
1272 $pager = new LogPager( $loglist, array('move', 'delete'), false,
1273 $this->mTitle->getPrefixedText(), '', array( "log_action != 'revision'" ) );
1274 if( $pager->getNumRows() > 0 ) {
1275 $pager->mLimit = 10;
1276 $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1277 $wgOut->addWikiMsg( 'moveddeleted-notice' );
1278 $wgOut->addHTML(
1279 $loglist->beginLogEventsList() .
1280 $pager->getBody() .
1281 $loglist->endLogEventsList()
1282 );
1283 if( $pager->getNumRows() > 10 ) {
1284 $wgOut->addHTML( $wgUser->getSkin()->link(
1285 SpecialPage::getTitleFor( 'Log' ),
1286 wfMsgHtml( 'log-fulllog' ),
1287 array(),
1288 array( 'page' => $this->mTitle->getPrefixedText() )
1289 ) );
1290 }
1291 $wgOut->addHTML( '</div>' );
1292 }
1293 }
1294
1295 /*
1296 * Should the parser cache be used?
1297 */
1298 public function useParserCache( $oldid ) {
1299 global $wgUser, $wgEnableParserCache;
1300
1301 return $wgEnableParserCache
1302 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1303 && $this->exists()
1304 && empty( $oldid )
1305 && !$this->mTitle->isCssOrJsPage()
1306 && !$this->mTitle->isCssJsSubpage();
1307 }
1308
1309 /**
1310 * Execute the uncached parse for action=view
1311 */
1312 public function doViewParse() {
1313 global $wgOut;
1314 $oldid = $this->getOldID();
1315 $useParserCache = $this->useParserCache( $oldid );
1316 $parserOptions = clone $this->getParserOptions();
1317 # Render printable version, use printable version cache
1318 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1319 # Don't show section-edit links on old revisions... this way lies madness.
1320 $parserOptions->setEditSection( $this->isCurrent() );
1321 $useParserCache = $this->useParserCache( $oldid );
1322 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1323 }
1324
1325 /**
1326 * Try to fetch an expired entry from the parser cache. If it is present,
1327 * output it and return true. If it is not present, output nothing and
1328 * return false. This is used as a callback function for
1329 * PoolCounter::executeProtected().
1330 */
1331 public function tryDirtyCache() {
1332 global $wgOut;
1333 $parserCache = ParserCache::singleton();
1334 $options = $this->getParserOptions();
1335 $options->setIsPrintable( $wgOut->isPrintable() );
1336 $output = $parserCache->getDirty( $this, $options );
1337 if ( $output ) {
1338 wfDebug( __METHOD__.": sending dirty output\n" );
1339 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1340 $wgOut->setSquidMaxage( 0 );
1341 $this->mParserOutput = $output;
1342 $wgOut->addParserOutput( $output );
1343 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1344 return true;
1345 } else {
1346 wfDebugLog( 'dirty', "dirty missing\n" );
1347 wfDebug( __METHOD__.": no dirty cache\n" );
1348 return false;
1349 }
1350 }
1351
1352 /**
1353 * Show an error page for an error from the pool counter.
1354 * @param $status Status
1355 */
1356 public function showPoolError( $status ) {
1357 global $wgOut;
1358 $wgOut->clearHTML(); // for release() errors
1359 $wgOut->enableClientCache( false );
1360 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1361 $wgOut->addWikiText(
1362 '<div class="errorbox">' .
1363 $status->getWikiText( false, 'view-pool-error' ) .
1364 '</div>'
1365 );
1366 }
1367
1368 /**
1369 * View redirect
1370 * @param $target Title object or Array of destination(s) to redirect
1371 * @param $appendSubtitle Boolean [optional]
1372 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1373 */
1374 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1375 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
1376 # Display redirect
1377 if( !is_array( $target ) ) {
1378 $target = array( $target );
1379 }
1380 $imageDir = $wgContLang->getDir();
1381 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1382 $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1383 $alt2 = $wgContLang->isRTL() ? '&larr;' : '&rarr;'; // should -> and <- be used instead of entities?
1384
1385 if( $appendSubtitle ) {
1386 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1387 }
1388 $sk = $wgUser->getSkin();
1389 // the loop prepends the arrow image before the link, so the first case needs to be outside
1390 $title = array_shift( $target );
1391 if( $forceKnown ) {
1392 $link = $sk->link(
1393 $title,
1394 htmlspecialchars( $title->getFullText() ),
1395 array(),
1396 array(),
1397 array( 'known', 'noclasses' )
1398 );
1399 } else {
1400 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1401 }
1402 // automatically append redirect=no to each link, since most of them are redirect pages themselves
1403 foreach( $target as $rt ) {
1404 if( $forceKnown ) {
1405 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1406 . $sk->link(
1407 $rt,
1408 htmlspecialchars( $rt->getFullText() ),
1409 array(),
1410 array(),
1411 array( 'known', 'noclasses' )
1412 );
1413 } else {
1414 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1415 . $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
1416 }
1417 }
1418 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1419 '<span class="redirectText">'.$link.'</span>';
1420
1421 }
1422
1423 public function addTrackbacks() {
1424 global $wgOut, $wgUser;
1425 $dbr = wfGetDB( DB_SLAVE );
1426 $tbs = $dbr->select( 'trackbacks',
1427 array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1428 array('tb_page' => $this->getID() )
1429 );
1430 if( !$dbr->numRows($tbs) ) return;
1431
1432 $tbtext = "";
1433 while( $o = $dbr->fetchObject($tbs) ) {
1434 $rmvtxt = "";
1435 if( $wgUser->isAllowed( 'trackback' ) ) {
1436 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid=" .
1437 $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
1438 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1439 }
1440 $tbtext .= "\n";
1441 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
1442 $o->tb_title,
1443 $o->tb_url,
1444 $o->tb_ex,
1445 $o->tb_name,
1446 $rmvtxt);
1447 }
1448 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>$1</div>\n", array( 'trackbackbox', $tbtext ) );
1449 $this->mTitle->invalidateCache();
1450 }
1451
1452 public function deletetrackback() {
1453 global $wgUser, $wgRequest, $wgOut;
1454 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1455 $wgOut->addWikiMsg( 'sessionfailure' );
1456 return;
1457 }
1458
1459 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1460 if( count($permission_errors) ) {
1461 $wgOut->showPermissionsErrorPage( $permission_errors );
1462 return;
1463 }
1464
1465 $db = wfGetDB( DB_MASTER );
1466 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1467
1468 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1469 $this->mTitle->invalidateCache();
1470 }
1471
1472 public function render() {
1473 global $wgOut;
1474 $wgOut->setArticleBodyOnly(true);
1475 $this->view();
1476 }
1477
1478 /**
1479 * Handle action=purge
1480 */
1481 public function purge() {
1482 global $wgUser, $wgRequest, $wgOut;
1483 if( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
1484 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1485 $this->doPurge();
1486 $this->view();
1487 }
1488 } else {
1489 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1490 $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1491 $form = "<form method=\"post\" action=\"$action\">\n" .
1492 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1493 "</form>\n";
1494 $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1495 $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1496 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1497 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1498 $wgOut->addHTML( $top . $form . $bottom );
1499 }
1500 }
1501
1502 /**
1503 * Perform the actions of a page purging
1504 */
1505 public function doPurge() {
1506 global $wgUseSquid;
1507 // Invalidate the cache
1508 $this->mTitle->invalidateCache();
1509
1510 if( $wgUseSquid ) {
1511 // Commit the transaction before the purge is sent
1512 $dbw = wfGetDB( DB_MASTER );
1513 $dbw->immediateCommit();
1514
1515 // Send purge
1516 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1517 $update->doUpdate();
1518 }
1519 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1520 global $wgMessageCache;
1521 if( $this->getID() == 0 ) {
1522 $text = false;
1523 } else {
1524 $text = $this->getRawText();
1525 }
1526 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
1527 }
1528 }
1529
1530 /**
1531 * Insert a new empty page record for this article.
1532 * This *must* be followed up by creating a revision
1533 * and running $this->updateToLatest( $rev_id );
1534 * or else the record will be left in a funky state.
1535 * Best if all done inside a transaction.
1536 *
1537 * @param $dbw Database
1538 * @return int The newly created page_id key, or false if the title already existed
1539 * @private
1540 */
1541 public function insertOn( $dbw ) {
1542 wfProfileIn( __METHOD__ );
1543
1544 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1545 $dbw->insert( 'page', array(
1546 'page_id' => $page_id,
1547 'page_namespace' => $this->mTitle->getNamespace(),
1548 'page_title' => $this->mTitle->getDBkey(),
1549 'page_counter' => 0,
1550 'page_restrictions' => '',
1551 'page_is_redirect' => 0, # Will set this shortly...
1552 'page_is_new' => 1,
1553 'page_random' => wfRandom(),
1554 'page_touched' => $dbw->timestamp(),
1555 'page_latest' => 0, # Fill this in shortly...
1556 'page_len' => 0, # Fill this in shortly...
1557 ), __METHOD__, 'IGNORE' );
1558
1559 $affected = $dbw->affectedRows();
1560 if( $affected ) {
1561 $newid = $dbw->insertId();
1562 $this->mTitle->resetArticleId( $newid );
1563 }
1564 wfProfileOut( __METHOD__ );
1565 return $affected ? $newid : false;
1566 }
1567
1568 /**
1569 * Update the page record to point to a newly saved revision.
1570 *
1571 * @param $dbw Database object
1572 * @param $revision Revision: For ID number, and text used to set
1573 length and redirect status fields
1574 * @param $lastRevision Integer: if given, will not overwrite the page field
1575 * when different from the currently set value.
1576 * Giving 0 indicates the new page flag should be set
1577 * on.
1578 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1579 * removing rows in redirect table.
1580 * @return bool true on success, false on failure
1581 * @private
1582 */
1583 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1584 wfProfileIn( __METHOD__ );
1585
1586 $text = $revision->getText();
1587 $rt = Title::newFromRedirect( $text );
1588
1589 $conditions = array( 'page_id' => $this->getId() );
1590 if( !is_null( $lastRevision ) ) {
1591 # An extra check against threads stepping on each other
1592 $conditions['page_latest'] = $lastRevision;
1593 }
1594
1595 $dbw->update( 'page',
1596 array( /* SET */
1597 'page_latest' => $revision->getId(),
1598 'page_touched' => $dbw->timestamp(),
1599 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1600 'page_is_redirect' => $rt !== NULL ? 1 : 0,
1601 'page_len' => strlen( $text ),
1602 ),
1603 $conditions,
1604 __METHOD__ );
1605
1606 $result = $dbw->affectedRows() != 0;
1607 if( $result ) {
1608 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1609 }
1610
1611 wfProfileOut( __METHOD__ );
1612 return $result;
1613 }
1614
1615 /**
1616 * Add row to the redirect table if this is a redirect, remove otherwise.
1617 *
1618 * @param $dbw Database
1619 * @param $redirectTitle a title object pointing to the redirect target,
1620 * or NULL if this is not a redirect
1621 * @param $lastRevIsRedirect If given, will optimize adding and
1622 * removing rows in redirect table.
1623 * @return bool true on success, false on failure
1624 * @private
1625 */
1626 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1627 // Always update redirects (target link might have changed)
1628 // Update/Insert if we don't know if the last revision was a redirect or not
1629 // Delete if changing from redirect to non-redirect
1630 $isRedirect = !is_null($redirectTitle);
1631 if($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
1632 wfProfileIn( __METHOD__ );
1633 if( $isRedirect ) {
1634 // This title is a redirect, Add/Update row in the redirect table
1635 $set = array( /* SET */
1636 'rd_namespace' => $redirectTitle->getNamespace(),
1637 'rd_title' => $redirectTitle->getDBkey(),
1638 'rd_from' => $this->getId(),
1639 );
1640 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1641 } else {
1642 // This is not a redirect, remove row from redirect table
1643 $where = array( 'rd_from' => $this->getId() );
1644 $dbw->delete( 'redirect', $where, __METHOD__);
1645 }
1646 if( $this->getTitle()->getNamespace() == NS_FILE ) {
1647 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1648 }
1649 wfProfileOut( __METHOD__ );
1650 return ( $dbw->affectedRows() != 0 );
1651 }
1652 return true;
1653 }
1654
1655 /**
1656 * If the given revision is newer than the currently set page_latest,
1657 * update the page record. Otherwise, do nothing.
1658 *
1659 * @param $dbw Database object
1660 * @param $revision Revision object
1661 */
1662 public function updateIfNewerOn( &$dbw, $revision ) {
1663 wfProfileIn( __METHOD__ );
1664 $row = $dbw->selectRow(
1665 array( 'revision', 'page' ),
1666 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1667 array(
1668 'page_id' => $this->getId(),
1669 'page_latest=rev_id' ),
1670 __METHOD__ );
1671 if( $row ) {
1672 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1673 wfProfileOut( __METHOD__ );
1674 return false;
1675 }
1676 $prev = $row->rev_id;
1677 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1678 } else {
1679 # No or missing previous revision; mark the page as new
1680 $prev = 0;
1681 $lastRevIsRedirect = null;
1682 }
1683 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1684 wfProfileOut( __METHOD__ );
1685 return $ret;
1686 }
1687
1688 /**
1689 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1690 * @return string Complete article text, or null if error
1691 */
1692 public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
1693 wfProfileIn( __METHOD__ );
1694 if( strval( $section ) == '' ) {
1695 // Whole-page edit; let the whole text through
1696 } else {
1697 if( is_null($edittime) ) {
1698 $rev = Revision::newFromTitle( $this->mTitle );
1699 } else {
1700 $dbw = wfGetDB( DB_MASTER );
1701 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1702 }
1703 if( !$rev ) {
1704 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1705 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1706 return null;
1707 }
1708 $oldtext = $rev->getText();
1709
1710 if( $section == 'new' ) {
1711 # Inserting a new section
1712 $subject = $summary ? wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1713 $text = strlen( trim( $oldtext ) ) > 0
1714 ? "{$oldtext}\n\n{$subject}{$text}"
1715 : "{$subject}{$text}";
1716 } else {
1717 # Replacing an existing section; roll out the big guns
1718 global $wgParser;
1719 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1720 }
1721 }
1722 wfProfileOut( __METHOD__ );
1723 return $text;
1724 }
1725
1726 /**
1727 * This function is not deprecated until somebody fixes the core not to use
1728 * it. Nevertheless, use Article::doEdit() instead.
1729 */
1730 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1731 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1732 ( $isminor ? EDIT_MINOR : 0 ) |
1733 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1734 ( $bot ? EDIT_FORCE_BOT : 0 );
1735
1736 # If this is a comment, add the summary as headline
1737 if( $comment && $summary != "" ) {
1738 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1739 }
1740
1741 $this->doEdit( $text, $summary, $flags );
1742
1743 $dbw = wfGetDB( DB_MASTER );
1744 if($watchthis) {
1745 if(!$this->mTitle->userIsWatching()) {
1746 $dbw->begin();
1747 $this->doWatch();
1748 $dbw->commit();
1749 }
1750 } else {
1751 if( $this->mTitle->userIsWatching() ) {
1752 $dbw->begin();
1753 $this->doUnwatch();
1754 $dbw->commit();
1755 }
1756 }
1757 $this->doRedirect( $this->isRedirect( $text ) );
1758 }
1759
1760 /**
1761 * @deprecated use Article::doEdit()
1762 */
1763 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1764 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1765 ( $minor ? EDIT_MINOR : 0 ) |
1766 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1767
1768 $status = $this->doEdit( $text, $summary, $flags );
1769 if( !$status->isOK() ) {
1770 return false;
1771 }
1772
1773 $dbw = wfGetDB( DB_MASTER );
1774 if( $watchthis ) {
1775 if(!$this->mTitle->userIsWatching()) {
1776 $dbw->begin();
1777 $this->doWatch();
1778 $dbw->commit();
1779 }
1780 } else {
1781 if( $this->mTitle->userIsWatching() ) {
1782 $dbw->begin();
1783 $this->doUnwatch();
1784 $dbw->commit();
1785 }
1786 }
1787
1788 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1789 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1790
1791 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1792 return true;
1793 }
1794
1795 /**
1796 * Article::doEdit()
1797 *
1798 * Change an existing article or create a new article. Updates RC and all necessary caches,
1799 * optionally via the deferred update array.
1800 *
1801 * $wgUser must be set before calling this function.
1802 *
1803 * @param $text String: new text
1804 * @param $summary String: edit summary
1805 * @param $flags Integer bitfield:
1806 * EDIT_NEW
1807 * Article is known or assumed to be non-existent, create a new one
1808 * EDIT_UPDATE
1809 * Article is known or assumed to be pre-existing, update it
1810 * EDIT_MINOR
1811 * Mark this edit minor, if the user is allowed to do so
1812 * EDIT_SUPPRESS_RC
1813 * Do not log the change in recentchanges
1814 * EDIT_FORCE_BOT
1815 * Mark the edit a "bot" edit regardless of user rights
1816 * EDIT_DEFER_UPDATES
1817 * Defer some of the updates until the end of index.php
1818 * EDIT_AUTOSUMMARY
1819 * Fill in blank summaries with generated text where possible
1820 *
1821 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1822 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1823 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1824 * edit-already-exists error will be returned. These two conditions are also possible with
1825 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1826 *
1827 * @param $baseRevId the revision ID this edit was based off, if any
1828 * @param $user Optional user object, $wgUser will be used if not passed
1829 *
1830 * @return Status object. Possible errors:
1831 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1832 * edit-gone-missing: In update mode, but the article didn't exist
1833 * edit-conflict: In update mode, the article changed unexpectedly
1834 * edit-no-change: Warning that the text was the same as before
1835 * edit-already-exists: In creation mode, but the article already exists
1836 *
1837 * Extensions may define additional errors.
1838 *
1839 * $return->value will contain an associative array with members as follows:
1840 * new: Boolean indicating if the function attempted to create a new article
1841 * revision: The revision object for the inserted revision, or null
1842 *
1843 * Compatibility note: this function previously returned a boolean value indicating success/failure
1844 */
1845 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1846 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1847
1848 # Low-level sanity check
1849 if( $this->mTitle->getText() == '' ) {
1850 throw new MWException( 'Something is trying to edit an article with an empty title' );
1851 }
1852
1853 wfProfileIn( __METHOD__ );
1854
1855 $user = is_null($user) ? $wgUser : $user;
1856 $status = Status::newGood( array() );
1857
1858 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1859 $this->loadPageData();
1860
1861 if( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1862 $aid = $this->mTitle->getArticleID();
1863 if( $aid ) {
1864 $flags |= EDIT_UPDATE;
1865 } else {
1866 $flags |= EDIT_NEW;
1867 }
1868 }
1869
1870 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1871 $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
1872 {
1873 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1874 wfProfileOut( __METHOD__ );
1875 if( $status->isOK() ) {
1876 $status->fatal( 'edit-hook-aborted');
1877 }
1878 return $status;
1879 }
1880
1881 # Silently ignore EDIT_MINOR if not allowed
1882 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed('minoredit');
1883 $bot = $flags & EDIT_FORCE_BOT;
1884
1885 $oldtext = $this->getRawText(); // current revision
1886 $oldsize = strlen( $oldtext );
1887
1888 # Provide autosummaries if one is not provided and autosummaries are enabled.
1889 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1890 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1891 }
1892
1893 $editInfo = $this->prepareTextForEdit( $text );
1894 $text = $editInfo->pst;
1895 $newsize = strlen( $text );
1896
1897 $dbw = wfGetDB( DB_MASTER );
1898 $now = wfTimestampNow();
1899
1900 if( $flags & EDIT_UPDATE ) {
1901 # Update article, but only if changed.
1902 $status->value['new'] = false;
1903 # Make sure the revision is either completely inserted or not inserted at all
1904 if( !$wgDBtransactions ) {
1905 $userAbort = ignore_user_abort( true );
1906 }
1907
1908 $revisionId = 0;
1909
1910 $changed = ( strcmp( $text, $oldtext ) != 0 );
1911
1912 if( $changed ) {
1913 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1914 - (int)$this->isCountable( $oldtext );
1915 $this->mTotalAdjustment = 0;
1916
1917 if( !$this->mLatest ) {
1918 # Article gone missing
1919 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1920 $status->fatal( 'edit-gone-missing' );
1921 wfProfileOut( __METHOD__ );
1922 return $status;
1923 }
1924
1925 $revision = new Revision( array(
1926 'page' => $this->getId(),
1927 'comment' => $summary,
1928 'minor_edit' => $isminor,
1929 'text' => $text,
1930 'parent_id' => $this->mLatest,
1931 'user' => $user->getId(),
1932 'user_text' => $user->getName(),
1933 ) );
1934
1935 $dbw->begin();
1936 $revisionId = $revision->insertOn( $dbw );
1937
1938 # Update page
1939 #
1940 # Note that we use $this->mLatest instead of fetching a value from the master DB
1941 # during the course of this function. This makes sure that EditPage can detect
1942 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1943 # before this function is called. A previous function used a separate query, this
1944 # creates a window where concurrent edits can cause an ignored edit conflict.
1945 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
1946
1947 if( !$ok ) {
1948 /* Belated edit conflict! Run away!! */
1949 $status->fatal( 'edit-conflict' );
1950 # Delete the invalid revision if the DB is not transactional
1951 if( !$wgDBtransactions ) {
1952 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1953 }
1954 $revisionId = 0;
1955 $dbw->rollback();
1956 } else {
1957 global $wgUseRCPatrol;
1958 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) );
1959 # Update recentchanges
1960 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1961 # Mark as patrolled if the user can do so
1962 $patrolled = $wgUseRCPatrol && $this->mTitle->userCan('autopatrol');
1963 # Add RC row to the DB
1964 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1965 $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1966 $revisionId, $patrolled
1967 );
1968 # Log auto-patrolled edits
1969 if( $patrolled ) {
1970 PatrolLog::record( $rc, true );
1971 }
1972 }
1973 $user->incEditCount();
1974 $dbw->commit();
1975 }
1976 } else {
1977 $status->warning( 'edit-no-change' );
1978 $revision = null;
1979 // Keep the same revision ID, but do some updates on it
1980 $revisionId = $this->getRevIdFetched();
1981 // Update page_touched, this is usually implicit in the page update
1982 // Other cache updates are done in onArticleEdit()
1983 $this->mTitle->invalidateCache();
1984 }
1985
1986 if( !$wgDBtransactions ) {
1987 ignore_user_abort( $userAbort );
1988 }
1989 // Now that ignore_user_abort is restored, we can respond to fatal errors
1990 if( !$status->isOK() ) {
1991 wfProfileOut( __METHOD__ );
1992 return $status;
1993 }
1994
1995 # Invalidate cache of this article and all pages using this article
1996 # as a template. Partly deferred.
1997 Article::onArticleEdit( $this->mTitle );
1998 # Update links tables, site stats, etc.
1999 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
2000 } else {
2001 # Create new article
2002 $status->value['new'] = true;
2003
2004 # Set statistics members
2005 # We work out if it's countable after PST to avoid counter drift
2006 # when articles are created with {{subst:}}
2007 $this->mGoodAdjustment = (int)$this->isCountable( $text );
2008 $this->mTotalAdjustment = 1;
2009
2010 $dbw->begin();
2011
2012 # Add the page record; stake our claim on this title!
2013 # This will return false if the article already exists
2014 $newid = $this->insertOn( $dbw );
2015
2016 if( $newid === false ) {
2017 $dbw->rollback();
2018 $status->fatal( 'edit-already-exists' );
2019 wfProfileOut( __METHOD__ );
2020 return $status;
2021 }
2022
2023 # Save the revision text...
2024 $revision = new Revision( array(
2025 'page' => $newid,
2026 'comment' => $summary,
2027 'minor_edit' => $isminor,
2028 'text' => $text,
2029 'user' => $user->getId(),
2030 'user_text' => $user->getName(),
2031 ) );
2032 $revisionId = $revision->insertOn( $dbw );
2033
2034 $this->mTitle->resetArticleID( $newid );
2035
2036 # Update the page record with revision data
2037 $this->updateRevisionOn( $dbw, $revision, 0 );
2038
2039 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) );
2040 # Update recentchanges
2041 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
2042 global $wgUseRCPatrol, $wgUseNPPatrol;
2043 # Mark as patrolled if the user can do so
2044 $patrolled = ($wgUseRCPatrol || $wgUseNPPatrol) && $this->mTitle->userCan('autopatrol');
2045 # Add RC row to the DB
2046 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
2047 '', strlen($text), $revisionId, $patrolled );
2048 # Log auto-patrolled edits
2049 if( $patrolled ) {
2050 PatrolLog::record( $rc, true );
2051 }
2052 }
2053 $user->incEditCount();
2054 $dbw->commit();
2055
2056 # Update links, etc.
2057 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
2058
2059 # Clear caches
2060 Article::onArticleCreate( $this->mTitle );
2061
2062 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2063 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
2064 }
2065
2066 # Do updates right now unless deferral was requested
2067 if( !( $flags & EDIT_DEFER_UPDATES ) ) {
2068 wfDoUpdates();
2069 }
2070
2071 // Return the new revision (or null) to the caller
2072 $status->value['revision'] = $revision;
2073
2074 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2075 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
2076
2077 wfProfileOut( __METHOD__ );
2078 return $status;
2079 }
2080
2081 /**
2082 * @deprecated wrapper for doRedirect
2083 */
2084 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
2085 wfDeprecated( __METHOD__ );
2086 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
2087 }
2088
2089 /**
2090 * Output a redirect back to the article.
2091 * This is typically used after an edit.
2092 *
2093 * @param $noRedir Boolean: add redirect=no
2094 * @param $sectionAnchor String: section to redirect to, including "#"
2095 * @param $extraQuery String: extra query params
2096 */
2097 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2098 global $wgOut;
2099 if( $noRedir ) {
2100 $query = 'redirect=no';
2101 if( $extraQuery )
2102 $query .= "&$query";
2103 } else {
2104 $query = $extraQuery;
2105 }
2106 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
2107 }
2108
2109 /**
2110 * Mark this particular edit/page as patrolled
2111 */
2112 public function markpatrolled() {
2113 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
2114 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2115
2116 # If we haven't been given an rc_id value, we can't do anything
2117 $rcid = (int) $wgRequest->getVal('rcid');
2118 $rc = RecentChange::newFromId($rcid);
2119 if( is_null($rc) ) {
2120 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2121 return;
2122 }
2123
2124 #It would be nice to see where the user had actually come from, but for now just guess
2125 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
2126 $return = SpecialPage::getTitleFor( $returnto );
2127
2128 $dbw = wfGetDB( DB_MASTER );
2129 $errors = $rc->doMarkPatrolled();
2130
2131 if( in_array(array('rcpatroldisabled'), $errors) ) {
2132 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2133 return;
2134 }
2135
2136 if( in_array(array('hookaborted'), $errors) ) {
2137 // The hook itself has handled any output
2138 return;
2139 }
2140
2141 if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
2142 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2143 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2144 $wgOut->returnToMain( false, $return );
2145 return;
2146 }
2147
2148 if( !empty($errors) ) {
2149 $wgOut->showPermissionsErrorPage( $errors );
2150 return;
2151 }
2152
2153 # Inform the user
2154 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2155 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
2156 $wgOut->returnToMain( false, $return );
2157 }
2158
2159 /**
2160 * User-interface handler for the "watch" action
2161 */
2162
2163 public function watch() {
2164 global $wgUser, $wgOut;
2165 if( $wgUser->isAnon() ) {
2166 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2167 return;
2168 }
2169 if( wfReadOnly() ) {
2170 $wgOut->readOnlyPage();
2171 return;
2172 }
2173 if( $this->doWatch() ) {
2174 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2175 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2176 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
2177 }
2178 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2179 }
2180
2181 /**
2182 * Add this page to $wgUser's watchlist
2183 * @return bool true on successful watch operation
2184 */
2185 public function doWatch() {
2186 global $wgUser;
2187 if( $wgUser->isAnon() ) {
2188 return false;
2189 }
2190 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
2191 $wgUser->addWatch( $this->mTitle );
2192 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
2193 }
2194 return false;
2195 }
2196
2197 /**
2198 * User interface handler for the "unwatch" action.
2199 */
2200 public function unwatch() {
2201 global $wgUser, $wgOut;
2202 if( $wgUser->isAnon() ) {
2203 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2204 return;
2205 }
2206 if( wfReadOnly() ) {
2207 $wgOut->readOnlyPage();
2208 return;
2209 }
2210 if( $this->doUnwatch() ) {
2211 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2212 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2213 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
2214 }
2215 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2216 }
2217
2218 /**
2219 * Stop watching a page
2220 * @return bool true on successful unwatch
2221 */
2222 public function doUnwatch() {
2223 global $wgUser;
2224 if( $wgUser->isAnon() ) {
2225 return false;
2226 }
2227 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
2228 $wgUser->removeWatch( $this->mTitle );
2229 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
2230 }
2231 return false;
2232 }
2233
2234 /**
2235 * action=protect handler
2236 */
2237 public function protect() {
2238 $form = new ProtectionForm( $this );
2239 $form->execute();
2240 }
2241
2242 /**
2243 * action=unprotect handler (alias)
2244 */
2245 public function unprotect() {
2246 $this->protect();
2247 }
2248
2249 /**
2250 * Update the article's restriction field, and leave a log entry.
2251 *
2252 * @param $limit Array: set of restriction keys
2253 * @param $reason String
2254 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2255 * @param $expiry Array: per restriction type expiration
2256 * @return bool true on success
2257 */
2258 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2259 global $wgUser, $wgRestrictionTypes, $wgContLang;
2260
2261 $id = $this->mTitle->getArticleID();
2262 if ( $id <= 0 ) {
2263 wfDebug( "updateRestrictions failed: $id <= 0\n" );
2264 return false;
2265 }
2266
2267 if ( wfReadOnly() ) {
2268 wfDebug( "updateRestrictions failed: read-only\n" );
2269 return false;
2270 }
2271
2272 if ( !$this->mTitle->userCan( 'protect' ) ) {
2273 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2274 return false;
2275 }
2276
2277 if( !$cascade ) {
2278 $cascade = false;
2279 }
2280
2281 // Take this opportunity to purge out expired restrictions
2282 Title::purgeExpiredRestrictions();
2283
2284 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2285 # we expect a single selection, but the schema allows otherwise.
2286 $current = array();
2287 $updated = Article::flattenRestrictions( $limit );
2288 $changed = false;
2289 foreach( $wgRestrictionTypes as $action ) {
2290 if( isset( $expiry[$action] ) ) {
2291 # Get current restrictions on $action
2292 $aLimits = $this->mTitle->getRestrictions( $action );
2293 $current[$action] = implode( '', $aLimits );
2294 # Are any actual restrictions being dealt with here?
2295 $aRChanged = count($aLimits) || !empty($limit[$action]);
2296 # If something changed, we need to log it. Checking $aRChanged
2297 # assures that "unprotecting" a page that is not protected does
2298 # not log just because the expiry was "changed".
2299 if( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
2300 $changed = true;
2301 }
2302 }
2303 }
2304
2305 $current = Article::flattenRestrictions( $current );
2306
2307 $changed = ($changed || $current != $updated );
2308 $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade);
2309 $protect = ( $updated != '' );
2310
2311 # If nothing's changed, do nothing
2312 if( $changed ) {
2313 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2314
2315 $dbw = wfGetDB( DB_MASTER );
2316
2317 # Prepare a null revision to be added to the history
2318 $modified = $current != '' && $protect;
2319 if( $protect ) {
2320 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
2321 } else {
2322 $comment_type = 'unprotectedarticle';
2323 }
2324 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
2325
2326 # Only restrictions with the 'protect' right can cascade...
2327 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2328 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2329 # The schema allows multiple restrictions
2330 if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction))
2331 $cascade = false;
2332 $cascade_description = '';
2333 if( $cascade ) {
2334 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
2335 }
2336
2337 if( $reason )
2338 $comment .= ": $reason";
2339
2340 $editComment = $comment;
2341 $encodedExpiry = array();
2342 $protect_description = '';
2343 foreach( $limit as $action => $restrictions ) {
2344 if ( !isset($expiry[$action]) )
2345 $expiry[$action] = 'infinite';
2346
2347 $encodedExpiry[$action] = Block::encodeExpiry($expiry[$action], $dbw );
2348 if( $restrictions != '' ) {
2349 $protect_description .= "[$action=$restrictions] (";
2350 if( $encodedExpiry[$action] != 'infinity' ) {
2351 $protect_description .= wfMsgForContent( 'protect-expiring',
2352 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2353 $wgContLang->date( $expiry[$action], false, false ) ,
2354 $wgContLang->time( $expiry[$action], false, false ) );
2355 } else {
2356 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2357 }
2358 $protect_description .= ') ';
2359 }
2360 }
2361 $protect_description = trim($protect_description);
2362
2363 if( $protect_description && $protect )
2364 $editComment .= " ($protect_description)";
2365 if( $cascade )
2366 $editComment .= "$cascade_description";
2367 # Update restrictions table
2368 foreach( $limit as $action => $restrictions ) {
2369 if($restrictions != '' ) {
2370 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
2371 array( 'pr_page' => $id,
2372 'pr_type' => $action,
2373 'pr_level' => $restrictions,
2374 'pr_cascade' => ($cascade && $action == 'edit') ? 1 : 0,
2375 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__ );
2376 } else {
2377 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2378 'pr_type' => $action ), __METHOD__ );
2379 }
2380 }
2381
2382 # Insert a null revision
2383 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2384 $nullRevId = $nullRevision->insertOn( $dbw );
2385
2386 $latest = $this->getLatest();
2387 # Update page record
2388 $dbw->update( 'page',
2389 array( /* SET */
2390 'page_touched' => $dbw->timestamp(),
2391 'page_restrictions' => '',
2392 'page_latest' => $nullRevId
2393 ), array( /* WHERE */
2394 'page_id' => $id
2395 ), 'Article::protect'
2396 );
2397
2398 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
2399 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2400
2401 # Update the protection log
2402 $log = new LogPage( 'protect' );
2403 if( $protect ) {
2404 $params = array($protect_description,$cascade ? 'cascade' : '');
2405 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason), $params );
2406 } else {
2407 $log->addEntry( 'unprotect', $this->mTitle, $reason );
2408 }
2409
2410 } # End hook
2411 } # End "changed" check
2412
2413 return true;
2414 }
2415
2416 /**
2417 * Take an array of page restrictions and flatten it to a string
2418 * suitable for insertion into the page_restrictions field.
2419 * @param $limit Array
2420 * @return String
2421 */
2422 protected static function flattenRestrictions( $limit ) {
2423 if( !is_array( $limit ) ) {
2424 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2425 }
2426 $bits = array();
2427 ksort( $limit );
2428 foreach( $limit as $action => $restrictions ) {
2429 if( $restrictions != '' ) {
2430 $bits[] = "$action=$restrictions";
2431 }
2432 }
2433 return implode( ':', $bits );
2434 }
2435
2436 /**
2437 * Auto-generates a deletion reason
2438 * @param &$hasHistory Boolean: whether the page has a history
2439 */
2440 public function generateReason( &$hasHistory ) {
2441 global $wgContLang;
2442 $dbw = wfGetDB( DB_MASTER );
2443 // Get the last revision
2444 $rev = Revision::newFromTitle( $this->mTitle );
2445 if( is_null( $rev ) )
2446 return false;
2447
2448 // Get the article's contents
2449 $contents = $rev->getText();
2450 $blank = false;
2451 // If the page is blank, use the text from the previous revision,
2452 // which can only be blank if there's a move/import/protect dummy revision involved
2453 if( $contents == '' ) {
2454 $prev = $rev->getPrevious();
2455 if( $prev ) {
2456 $contents = $prev->getText();
2457 $blank = true;
2458 }
2459 }
2460
2461 // Find out if there was only one contributor
2462 // Only scan the last 20 revisions
2463 $res = $dbw->select( 'revision', 'rev_user_text',
2464 array( 'rev_page' => $this->getID(), $dbw->bitAnd('rev_deleted', Revision::DELETED_USER) . ' = 0' ),
2465 __METHOD__,
2466 array( 'LIMIT' => 20 )
2467 );
2468 if( $res === false )
2469 // This page has no revisions, which is very weird
2470 return false;
2471
2472 $hasHistory = ( $res->numRows() > 1 );
2473 $row = $dbw->fetchObject( $res );
2474 $onlyAuthor = $row->rev_user_text;
2475 // Try to find a second contributor
2476 foreach( $res as $row ) {
2477 if( $row->rev_user_text != $onlyAuthor ) {
2478 $onlyAuthor = false;
2479 break;
2480 }
2481 }
2482 $dbw->freeResult( $res );
2483
2484 // Generate the summary with a '$1' placeholder
2485 if( $blank ) {
2486 // The current revision is blank and the one before is also
2487 // blank. It's just not our lucky day
2488 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2489 } else {
2490 if( $onlyAuthor )
2491 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2492 else
2493 $reason = wfMsgForContent( 'excontent', '$1' );
2494 }
2495
2496 if( $reason == '-' ) {
2497 // Allow these UI messages to be blanked out cleanly
2498 return '';
2499 }
2500
2501 // Replace newlines with spaces to prevent uglyness
2502 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2503 // Calculate the maximum amount of chars to get
2504 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2505 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2506 $contents = $wgContLang->truncate( $contents, $maxLength );
2507 // Remove possible unfinished links
2508 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2509 // Now replace the '$1' placeholder
2510 $reason = str_replace( '$1', $contents, $reason );
2511 return $reason;
2512 }
2513
2514
2515 /*
2516 * UI entry point for page deletion
2517 */
2518 public function delete() {
2519 global $wgUser, $wgOut, $wgRequest;
2520
2521 $confirm = $wgRequest->wasPosted() &&
2522 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2523
2524 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2525 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2526
2527 $reason = $this->DeleteReasonList;
2528
2529 if( $reason != 'other' && $this->DeleteReason != '' ) {
2530 // Entry from drop down menu + additional comment
2531 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason;
2532 } elseif( $reason == 'other' ) {
2533 $reason = $this->DeleteReason;
2534 }
2535 # Flag to hide all contents of the archived revisions
2536 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2537
2538 # This code desperately needs to be totally rewritten
2539
2540 # Read-only check...
2541 if( wfReadOnly() ) {
2542 $wgOut->readOnlyPage();
2543 return;
2544 }
2545
2546 # Check permissions
2547 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2548
2549 if( count( $permission_errors ) > 0 ) {
2550 $wgOut->showPermissionsErrorPage( $permission_errors );
2551 return;
2552 }
2553
2554 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2555
2556 # Better double-check that it hasn't been deleted yet!
2557 $dbw = wfGetDB( DB_MASTER );
2558 $conds = $this->mTitle->pageCond();
2559 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2560 if( $latest === false ) {
2561 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2562 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2563 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2564 return;
2565 }
2566
2567 # Hack for big sites
2568 $bigHistory = $this->isBigDeletion();
2569 if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2570 global $wgLang, $wgDeleteRevisionsLimit;
2571 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2572 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2573 return;
2574 }
2575
2576 if( $confirm ) {
2577 $this->doDelete( $reason, $suppress );
2578 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2579 $this->doWatch();
2580 } elseif( $this->mTitle->userIsWatching() ) {
2581 $this->doUnwatch();
2582 }
2583 return;
2584 }
2585
2586 // Generate deletion reason
2587 $hasHistory = false;
2588 if( !$reason ) $reason = $this->generateReason($hasHistory);
2589
2590 // If the page has a history, insert a warning
2591 if( $hasHistory && !$confirm ) {
2592 $skin = $wgUser->getSkin();
2593 $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ) ) . ' ' . $skin->historyLink() . '</strong>' );
2594 if( $bigHistory ) {
2595 global $wgLang, $wgDeleteRevisionsLimit;
2596 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2597 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2598 }
2599 }
2600
2601 return $this->confirmDelete( $reason );
2602 }
2603
2604 /**
2605 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2606 */
2607 public function isBigDeletion() {
2608 global $wgDeleteRevisionsLimit;
2609 if( $wgDeleteRevisionsLimit ) {
2610 $revCount = $this->estimateRevisionCount();
2611 return $revCount > $wgDeleteRevisionsLimit;
2612 }
2613 return false;
2614 }
2615
2616 /**
2617 * @return int approximate revision count
2618 */
2619 public function estimateRevisionCount() {
2620 $dbr = wfGetDB( DB_SLAVE );
2621 // For an exact count...
2622 //return $dbr->selectField( 'revision', 'COUNT(*)',
2623 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2624 return $dbr->estimateRowCount( 'revision', '*',
2625 array( 'rev_page' => $this->getId() ), __METHOD__ );
2626 }
2627
2628 /**
2629 * Get the last N authors
2630 * @param $num Integer: number of revisions to get
2631 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2632 * @return array Array of authors, duplicates not removed
2633 */
2634 public function getLastNAuthors( $num, $revLatest = 0 ) {
2635 wfProfileIn( __METHOD__ );
2636 // First try the slave
2637 // If that doesn't have the latest revision, try the master
2638 $continue = 2;
2639 $db = wfGetDB( DB_SLAVE );
2640 do {
2641 $res = $db->select( array( 'page', 'revision' ),
2642 array( 'rev_id', 'rev_user_text' ),
2643 array(
2644 'page_namespace' => $this->mTitle->getNamespace(),
2645 'page_title' => $this->mTitle->getDBkey(),
2646 'rev_page = page_id'
2647 ), __METHOD__, $this->getSelectOptions( array(
2648 'ORDER BY' => 'rev_timestamp DESC',
2649 'LIMIT' => $num
2650 ) )
2651 );
2652 if( !$res ) {
2653 wfProfileOut( __METHOD__ );
2654 return array();
2655 }
2656 $row = $db->fetchObject( $res );
2657 if( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2658 $db = wfGetDB( DB_MASTER );
2659 $continue--;
2660 } else {
2661 $continue = 0;
2662 }
2663 } while ( $continue );
2664
2665 $authors = array( $row->rev_user_text );
2666 while ( $row = $db->fetchObject( $res ) ) {
2667 $authors[] = $row->rev_user_text;
2668 }
2669 wfProfileOut( __METHOD__ );
2670 return $authors;
2671 }
2672
2673 /**
2674 * Output deletion confirmation dialog
2675 * @param $reason String: prefilled reason
2676 */
2677 public function confirmDelete( $reason ) {
2678 global $wgOut, $wgUser;
2679
2680 wfDebug( "Article::confirmDelete\n" );
2681
2682 $deleteBackLink = $wgUser->getSkin()->link(
2683 $this->mTitle,
2684 null,
2685 array(),
2686 array(),
2687 array( 'known', 'noclasses' )
2688 );
2689 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2690 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2691 $wgOut->addWikiMsg( 'confirmdeletetext' );
2692
2693 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2694
2695 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2696 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2697 <td></td>
2698 <td class='mw-input'><strong>" .
2699 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
2700 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2701 "</strong></td>
2702 </tr>";
2703 } else {
2704 $suppress = '';
2705 }
2706 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
2707
2708 $form = Xml::openElement( 'form', array( 'method' => 'post',
2709 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2710 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2711 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2712 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2713 "<tr id=\"wpDeleteReasonListRow\">
2714 <td class='mw-label'>" .
2715 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2716 "</td>
2717 <td class='mw-input'>" .
2718 Xml::listDropDown( 'wpDeleteReasonList',
2719 wfMsgForContent( 'deletereason-dropdown' ),
2720 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2721 "</td>
2722 </tr>
2723 <tr id=\"wpDeleteReasonRow\">
2724 <td class='mw-label'>" .
2725 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2726 "</td>
2727 <td class='mw-input'>" .
2728 Html::input( 'wpReason', $reason, 'text', array(
2729 'size' => '60',
2730 'maxlength' => '255',
2731 'tabindex' => '2',
2732 'id' => 'wpReason',
2733 'autofocus'
2734 ) ) .
2735 "</td>
2736 </tr>
2737 <tr>
2738 <td></td>
2739 <td class='mw-input'>" .
2740 Xml::checkLabel( wfMsg( 'watchthis' ),
2741 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2742 "</td>
2743 </tr>
2744 $suppress
2745 <tr>
2746 <td></td>
2747 <td class='mw-submit'>" .
2748 Xml::submitButton( wfMsg( 'deletepage' ),
2749 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2750 "</td>
2751 </tr>" .
2752 Xml::closeElement( 'table' ) .
2753 Xml::closeElement( 'fieldset' ) .
2754 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2755 Xml::closeElement( 'form' );
2756
2757 if( $wgUser->isAllowed( 'editinterface' ) ) {
2758 $skin = $wgUser->getSkin();
2759 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
2760 $link = $skin->link(
2761 $title,
2762 wfMsgHtml( 'delete-edit-reasonlist' ),
2763 array(),
2764 array( 'action' => 'edit' )
2765 );
2766 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2767 }
2768
2769 $wgOut->addHTML( $form );
2770 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2771 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2772 }
2773
2774 /**
2775 * Perform a deletion and output success or failure messages
2776 */
2777 public function doDelete( $reason, $suppress = false ) {
2778 global $wgOut, $wgUser;
2779 $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2780
2781 $error = '';
2782 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2783 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2784 $deleted = $this->mTitle->getPrefixedText();
2785
2786 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2787 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2788
2789 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2790
2791 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2792 $wgOut->returnToMain( false );
2793 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2794 }
2795 } else {
2796 if( $error == '' ) {
2797 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2798 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2799 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2800 } else {
2801 $wgOut->showFatalError( $error );
2802 }
2803 }
2804 }
2805
2806 /**
2807 * Back-end article deletion
2808 * Deletes the article with database consistency, writes logs, purges caches
2809 * Returns success
2810 */
2811 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2812 global $wgUseSquid, $wgDeferredUpdateList;
2813 global $wgUseTrackbacks;
2814
2815 wfDebug( __METHOD__."\n" );
2816
2817 $dbw = wfGetDB( DB_MASTER );
2818 $ns = $this->mTitle->getNamespace();
2819 $t = $this->mTitle->getDBkey();
2820 $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2821
2822 if( $t == '' || $id == 0 ) {
2823 return false;
2824 }
2825
2826 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getRawText() ), -1 );
2827 array_push( $wgDeferredUpdateList, $u );
2828
2829 // Bitfields to further suppress the content
2830 if( $suppress ) {
2831 $bitfield = 0;
2832 // This should be 15...
2833 $bitfield |= Revision::DELETED_TEXT;
2834 $bitfield |= Revision::DELETED_COMMENT;
2835 $bitfield |= Revision::DELETED_USER;
2836 $bitfield |= Revision::DELETED_RESTRICTED;
2837 } else {
2838 $bitfield = 'rev_deleted';
2839 }
2840
2841 $dbw->begin();
2842 // For now, shunt the revision data into the archive table.
2843 // Text is *not* removed from the text table; bulk storage
2844 // is left intact to avoid breaking block-compression or
2845 // immutable storage schemes.
2846 //
2847 // For backwards compatibility, note that some older archive
2848 // table entries will have ar_text and ar_flags fields still.
2849 //
2850 // In the future, we may keep revisions and mark them with
2851 // the rev_deleted field, which is reserved for this purpose.
2852 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2853 array(
2854 'ar_namespace' => 'page_namespace',
2855 'ar_title' => 'page_title',
2856 'ar_comment' => 'rev_comment',
2857 'ar_user' => 'rev_user',
2858 'ar_user_text' => 'rev_user_text',
2859 'ar_timestamp' => 'rev_timestamp',
2860 'ar_minor_edit' => 'rev_minor_edit',
2861 'ar_rev_id' => 'rev_id',
2862 'ar_text_id' => 'rev_text_id',
2863 'ar_text' => '\'\'', // Be explicit to appease
2864 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2865 'ar_len' => 'rev_len',
2866 'ar_page_id' => 'page_id',
2867 'ar_deleted' => $bitfield
2868 ), array(
2869 'page_id' => $id,
2870 'page_id = rev_page'
2871 ), __METHOD__
2872 );
2873
2874 # Delete restrictions for it
2875 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2876
2877 # Now that it's safely backed up, delete it
2878 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2879 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2880 if( !$ok ) {
2881 $dbw->rollback();
2882 return false;
2883 }
2884
2885 # Fix category table counts
2886 $cats = array();
2887 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
2888 foreach( $res as $row ) {
2889 $cats []= $row->cl_to;
2890 }
2891 $this->updateCategoryCounts( array(), $cats );
2892
2893 # If using cascading deletes, we can skip some explicit deletes
2894 if( !$dbw->cascadingDeletes() ) {
2895 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2896
2897 if($wgUseTrackbacks)
2898 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2899
2900 # Delete outgoing links
2901 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2902 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2903 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2904 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2905 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2906 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2907 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2908 }
2909
2910 # If using cleanup triggers, we can skip some manual deletes
2911 if( !$dbw->cleanupTriggers() ) {
2912 # Clean up recentchanges entries...
2913 $dbw->delete( 'recentchanges',
2914 array( 'rc_type != '.RC_LOG,
2915 'rc_namespace' => $this->mTitle->getNamespace(),
2916 'rc_title' => $this->mTitle->getDBkey() ),
2917 __METHOD__ );
2918 $dbw->delete( 'recentchanges',
2919 array( 'rc_type != '.RC_LOG, 'rc_cur_id' => $id ),
2920 __METHOD__ );
2921 }
2922
2923 # Clear caches
2924 Article::onArticleDelete( $this->mTitle );
2925
2926 # Clear the cached article id so the interface doesn't act like we exist
2927 $this->mTitle->resetArticleID( 0 );
2928
2929 # Log the deletion, if the page was suppressed, log it at Oversight instead
2930 $logtype = $suppress ? 'suppress' : 'delete';
2931 $log = new LogPage( $logtype );
2932
2933 # Make sure logging got through
2934 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
2935
2936 $dbw->commit();
2937
2938 return true;
2939 }
2940
2941 /**
2942 * Roll back the most recent consecutive set of edits to a page
2943 * from the same user; fails if there are no eligible edits to
2944 * roll back to, e.g. user is the sole contributor. This function
2945 * performs permissions checks on $wgUser, then calls commitRollback()
2946 * to do the dirty work
2947 *
2948 * @param $fromP String: Name of the user whose edits to rollback.
2949 * @param $summary String: Custom summary. Set to default summary if empty.
2950 * @param $token String: Rollback token.
2951 * @param $bot Boolean: If true, mark all reverted edits as bot.
2952 *
2953 * @param $resultDetails Array: contains result-specific array of additional values
2954 * 'alreadyrolled' : 'current' (rev)
2955 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2956 *
2957 * @return array of errors, each error formatted as
2958 * array(messagekey, param1, param2, ...).
2959 * On success, the array is empty. This array can also be passed to
2960 * OutputPage::showPermissionsErrorPage().
2961 */
2962 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2963 global $wgUser;
2964 $resultDetails = null;
2965
2966 # Check permissions
2967 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
2968 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
2969 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2970
2971 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2972 $errors[] = array( 'sessionfailure' );
2973
2974 if( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
2975 $errors[] = array( 'actionthrottledtext' );
2976 }
2977 # If there were errors, bail out now
2978 if( !empty( $errors ) )
2979 return $errors;
2980
2981 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2982 }
2983
2984 /**
2985 * Backend implementation of doRollback(), please refer there for parameter
2986 * and return value documentation
2987 *
2988 * NOTE: This function does NOT check ANY permissions, it just commits the
2989 * rollback to the DB Therefore, you should only call this function direct-
2990 * ly if you want to use custom permissions checks. If you don't, use
2991 * doRollback() instead.
2992 */
2993 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2994 global $wgUseRCPatrol, $wgUser, $wgLang;
2995 $dbw = wfGetDB( DB_MASTER );
2996
2997 if( wfReadOnly() ) {
2998 return array( array( 'readonlytext' ) );
2999 }
3000
3001 # Get the last editor
3002 $current = Revision::newFromTitle( $this->mTitle );
3003 if( is_null( $current ) ) {
3004 # Something wrong... no page?
3005 return array(array('notanarticle'));
3006 }
3007
3008 $from = str_replace( '_', ' ', $fromP );
3009 # User name given should match up with the top revision.
3010 # If the user was deleted then $from should be empty.
3011 if( $from != $current->getUserText() ) {
3012 $resultDetails = array( 'current' => $current );
3013 return array(array('alreadyrolled',
3014 htmlspecialchars($this->mTitle->getPrefixedText()),
3015 htmlspecialchars($fromP),
3016 htmlspecialchars($current->getUserText())
3017 ));
3018 }
3019
3020 # Get the last edit not by this guy...
3021 # Note: these may not be public values
3022 $user = intval( $current->getRawUser() );
3023 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3024 $s = $dbw->selectRow( 'revision',
3025 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3026 array( 'rev_page' => $current->getPage(),
3027 "rev_user != {$user} OR rev_user_text != {$user_text}"
3028 ), __METHOD__,
3029 array( 'USE INDEX' => 'page_timestamp',
3030 'ORDER BY' => 'rev_timestamp DESC' )
3031 );
3032 if( $s === false ) {
3033 # No one else ever edited this page
3034 return array(array('cantrollback'));
3035 } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
3036 # Only admins can see this text
3037 return array(array('notvisiblerev'));
3038 }
3039
3040 $set = array();
3041 if( $bot && $wgUser->isAllowed('markbotedits') ) {
3042 # Mark all reverted edits as bot
3043 $set['rc_bot'] = 1;
3044 }
3045 if( $wgUseRCPatrol ) {
3046 # Mark all reverted edits as patrolled
3047 $set['rc_patrolled'] = 1;
3048 }
3049
3050 if( count($set) ) {
3051 $dbw->update( 'recentchanges', $set,
3052 array( /* WHERE */
3053 'rc_cur_id' => $current->getPage(),
3054 'rc_user_text' => $current->getUserText(),
3055 "rc_timestamp > '{$s->rev_timestamp}'",
3056 ), __METHOD__
3057 );
3058 }
3059
3060 # Generate the edit summary if necessary
3061 $target = Revision::newFromId( $s->rev_id );
3062 if( empty( $summary ) ) {
3063 if( $from == '' ) { // no public user name
3064 $summary = wfMsgForContent( 'revertpage-nouser' );
3065 } else {
3066 $summary = wfMsgForContent( 'revertpage' );
3067 }
3068 }
3069
3070 # Allow the custom summary to use the same args as the default message
3071 $args = array(
3072 $target->getUserText(), $from, $s->rev_id,
3073 $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
3074 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
3075 );
3076 $summary = wfMsgReplaceArgs( $summary, $args );
3077
3078 # Save
3079 $flags = EDIT_UPDATE;
3080
3081 if( $wgUser->isAllowed('minoredit') )
3082 $flags |= EDIT_MINOR;
3083
3084 if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
3085 $flags |= EDIT_FORCE_BOT;
3086 # Actually store the edit
3087 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3088 if( !empty( $status->value['revision'] ) ) {
3089 $revId = $status->value['revision']->getId();
3090 } else {
3091 $revId = false;
3092 }
3093
3094 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3095
3096 $resultDetails = array(
3097 'summary' => $summary,
3098 'current' => $current,
3099 'target' => $target,
3100 'newid' => $revId
3101 );
3102 return array();
3103 }
3104
3105 /**
3106 * User interface for rollback operations
3107 */
3108 public function rollback() {
3109 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
3110 $details = null;
3111
3112 $result = $this->doRollback(
3113 $wgRequest->getVal( 'from' ),
3114 $wgRequest->getText( 'summary' ),
3115 $wgRequest->getVal( 'token' ),
3116 $wgRequest->getBool( 'bot' ),
3117 $details
3118 );
3119
3120 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
3121 $wgOut->rateLimited();
3122 return;
3123 }
3124 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
3125 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3126 $errArray = $result[0];
3127 $errMsg = array_shift( $errArray );
3128 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3129 if( isset( $details['current'] ) ){
3130 $current = $details['current'];
3131 if( $current->getComment() != '' ) {
3132 $wgOut->addWikiMsgArray( 'editcomment', array(
3133 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3134 }
3135 }
3136 return;
3137 }
3138 # Display permissions errors before read-only message -- there's no
3139 # point in misleading the user into thinking the inability to rollback
3140 # is only temporary.
3141 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3142 # array_diff is completely broken for arrays of arrays, sigh. Re-
3143 # move any 'readonlytext' error manually.
3144 $out = array();
3145 foreach( $result as $error ) {
3146 if( $error != array( 'readonlytext' ) ) {
3147 $out []= $error;
3148 }
3149 }
3150 $wgOut->showPermissionsErrorPage( $out );
3151 return;
3152 }
3153 if( $result == array( array( 'readonlytext' ) ) ) {
3154 $wgOut->readOnlyPage();
3155 return;
3156 }
3157
3158 $current = $details['current'];
3159 $target = $details['target'];
3160 $newId = $details['newid'];
3161 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3162 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3163 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3164 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3165 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3166 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3167 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3168 $wgOut->returnToMain( false, $this->mTitle );
3169
3170 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3171 $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
3172 $de->showDiff( '', '' );
3173 }
3174 }
3175
3176
3177 /**
3178 * Do standard deferred updates after page view
3179 */
3180 public function viewUpdates() {
3181 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3182 if ( wfReadOnly() ) {
3183 return;
3184 }
3185 # Don't update page view counters on views from bot users (bug 14044)
3186 if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
3187 Article::incViewCount( $this->getID() );
3188 $u = new SiteStatsUpdate( 1, 0, 0 );
3189 array_push( $wgDeferredUpdateList, $u );
3190 }
3191 # Update newtalk / watchlist notification status
3192 $wgUser->clearNotification( $this->mTitle );
3193 }
3194
3195 /**
3196 * Prepare text which is about to be saved.
3197 * Returns a stdclass with source, pst and output members
3198 */
3199 public function prepareTextForEdit( $text, $revid=null ) {
3200 if( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
3201 // Already prepared
3202 return $this->mPreparedEdit;
3203 }
3204 global $wgParser;
3205 $edit = (object)array();
3206 $edit->revid = $revid;
3207 $edit->newText = $text;
3208 $edit->pst = $this->preSaveTransform( $text );
3209 $options = $this->getParserOptions();
3210 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
3211 $edit->oldText = $this->getContent();
3212 $this->mPreparedEdit = $edit;
3213 return $edit;
3214 }
3215
3216 /**
3217 * Do standard deferred updates after page edit.
3218 * Update links tables, site stats, search index and message cache.
3219 * Purges pages that include this page if the text was changed here.
3220 * Every 100th edit, prune the recent changes table.
3221 *
3222 * @private
3223 * @param $text New text of the article
3224 * @param $summary Edit summary
3225 * @param $minoredit Minor edit
3226 * @param $timestamp_of_pagechange Timestamp associated with the page change
3227 * @param $newid rev_id value of the new revision
3228 * @param $changed Whether or not the content actually changed
3229 */
3230 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
3231 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
3232
3233 wfProfileIn( __METHOD__ );
3234
3235 # Parse the text
3236 # Be careful not to double-PST: $text is usually already PST-ed once
3237 if( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
3238 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
3239 $editInfo = $this->prepareTextForEdit( $text, $newid );
3240 } else {
3241 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
3242 $editInfo = $this->mPreparedEdit;
3243 }
3244
3245 # Save it to the parser cache
3246 if( $wgEnableParserCache ) {
3247 $popts = $this->getParserOptions();
3248 $parserCache = ParserCache::singleton();
3249 $parserCache->save( $editInfo->output, $this, $popts );
3250 }
3251
3252 # Update the links tables
3253 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
3254 $u->doUpdate();
3255
3256 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3257
3258 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3259 if( 0 == mt_rand( 0, 99 ) ) {
3260 // Flush old entries from the `recentchanges` table; we do this on
3261 // random requests so as to avoid an increase in writes for no good reason
3262 global $wgRCMaxAge;
3263 $dbw = wfGetDB( DB_MASTER );
3264 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3265 $recentchanges = $dbw->tableName( 'recentchanges' );
3266 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3267 $dbw->query( $sql );
3268 }
3269 }
3270
3271 $id = $this->getID();
3272 $title = $this->mTitle->getPrefixedDBkey();
3273 $shortTitle = $this->mTitle->getDBkey();
3274
3275 if( 0 == $id ) {
3276 wfProfileOut( __METHOD__ );
3277 return;
3278 }
3279
3280 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
3281 array_push( $wgDeferredUpdateList, $u );
3282 $u = new SearchUpdate( $id, $title, $text );
3283 array_push( $wgDeferredUpdateList, $u );
3284
3285 # If this is another user's talk page, update newtalk
3286 # Don't do this if $changed = false otherwise some idiot can null-edit a
3287 # load of user talk pages and piss people off, nor if it's a minor edit
3288 # by a properly-flagged bot.
3289 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
3290 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
3291 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3292 $other = User::newFromName( $shortTitle, false );
3293 if( !$other ) {
3294 wfDebug( __METHOD__.": invalid username\n" );
3295 } elseif( User::isIP( $shortTitle ) ) {
3296 // An anonymous user
3297 $other->setNewtalk( true );
3298 } elseif( $other->isLoggedIn() ) {
3299 $other->setNewtalk( true );
3300 } else {
3301 wfDebug( __METHOD__. ": don't need to notify a nonexistent user\n" );
3302 }
3303 }
3304 }
3305
3306 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3307 $wgMessageCache->replace( $shortTitle, $text );
3308 }
3309
3310 wfProfileOut( __METHOD__ );
3311 }
3312
3313 /**
3314 * Perform article updates on a special page creation.
3315 *
3316 * @param $rev Revision object
3317 *
3318 * @todo This is a shitty interface function. Kill it and replace the
3319 * other shitty functions like editUpdates and such so it's not needed
3320 * anymore.
3321 */
3322 public function createUpdates( $rev ) {
3323 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
3324 $this->mTotalAdjustment = 1;
3325 $this->editUpdates( $rev->getText(), $rev->getComment(),
3326 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3327 }
3328
3329 /**
3330 * Generate the navigation links when browsing through an article revisions
3331 * It shows the information as:
3332 * Revision as of \<date\>; view current revision
3333 * \<- Previous version | Next Version -\>
3334 *
3335 * @param $oldid String: revision ID of this article revision
3336 */
3337 public function setOldSubtitle( $oldid = 0 ) {
3338 global $wgLang, $wgOut, $wgUser, $wgRequest;
3339
3340 if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3341 return;
3342 }
3343
3344 $revision = Revision::newFromId( $oldid );
3345
3346 $current = ( $oldid == $this->mLatest );
3347 $td = $wgLang->timeanddate( $this->mTimestamp, true );
3348 $tddate = $wgLang->date( $this->mTimestamp, true );
3349 $tdtime = $wgLang->time( $this->mTimestamp, true );
3350 $sk = $wgUser->getSkin();
3351 $lnk = $current
3352 ? wfMsgHtml( 'currentrevisionlink' )
3353 : $sk->link(
3354 $this->mTitle,
3355 wfMsgHtml( 'currentrevisionlink' ),
3356 array(),
3357 array(),
3358 array( 'known', 'noclasses' )
3359 );
3360 $curdiff = $current
3361 ? wfMsgHtml( 'diff' )
3362 : $sk->link(
3363 $this->mTitle,
3364 wfMsgHtml( 'diff' ),
3365 array(),
3366 array(
3367 'diff' => 'cur',
3368 'oldid' => $oldid
3369 ),
3370 array( 'known', 'noclasses' )
3371 );
3372 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
3373 $prevlink = $prev
3374 ? $sk->link(
3375 $this->mTitle,
3376 wfMsgHtml( 'previousrevision' ),
3377 array(),
3378 array(
3379 'direction' => 'prev',
3380 'oldid' => $oldid
3381 ),
3382 array( 'known', 'noclasses' )
3383 )
3384 : wfMsgHtml( 'previousrevision' );
3385 $prevdiff = $prev
3386 ? $sk->link(
3387 $this->mTitle,
3388 wfMsgHtml( 'diff' ),
3389 array(),
3390 array(
3391 'diff' => 'prev',
3392 'oldid' => $oldid
3393 ),
3394 array( 'known', 'noclasses' )
3395 )
3396 : wfMsgHtml( 'diff' );
3397 $nextlink = $current
3398 ? wfMsgHtml( 'nextrevision' )
3399 : $sk->link(
3400 $this->mTitle,
3401 wfMsgHtml( 'nextrevision' ),
3402 array(),
3403 array(
3404 'direction' => 'next',
3405 'oldid' => $oldid
3406 ),
3407 array( 'known', 'noclasses' )
3408 );
3409 $nextdiff = $current
3410 ? wfMsgHtml( 'diff' )
3411 : $sk->link(
3412 $this->mTitle,
3413 wfMsgHtml( 'diff' ),
3414 array(),
3415 array(
3416 'diff' => 'next',
3417 'oldid' => $oldid
3418 ),
3419 array( 'known', 'noclasses' )
3420 );
3421
3422 $cdel='';
3423 if( $wgUser->isAllowed( 'deleterevision' ) ) {
3424 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
3425 if( $revision->isCurrent() ) {
3426 // We don't handle top deleted edits too well
3427 $cdel = wfMsgHtml( 'rev-delundel' );
3428 } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
3429 // If revision was hidden from sysops
3430 $cdel = wfMsgHtml( 'rev-delundel' );
3431 } else {
3432 $cdel = $sk->link(
3433 $revdel,
3434 wfMsgHtml('rev-delundel'),
3435 array(),
3436 array(
3437 'type' => 'revision',
3438 'target' => urlencode( $this->mTitle->getPrefixedDbkey() ),
3439 'ids' => urlencode( $oldid )
3440 ),
3441 array( 'known', 'noclasses' )
3442 );
3443 // Bolden oversighted content
3444 if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
3445 $cdel = "<strong>$cdel</strong>";
3446 }
3447 $cdel = "(<small>$cdel</small>) ";
3448 }
3449 $unhide = $wgRequest->getInt('unhide') == 1 && $wgUser->matchEditToken( $wgRequest->getVal('token'), $oldid );
3450 # Show user links if allowed to see them. If hidden, then show them only if requested...
3451 $userlinks = $sk->revUserTools( $revision, !$unhide );
3452
3453 $m = wfMsg( 'revision-info-current' );
3454 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3455 ? 'revision-info-current'
3456 : 'revision-info';
3457
3458 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3459 wfMsgExt(
3460 $infomsg,
3461 array( 'parseinline', 'replaceafter' ),
3462 $td,
3463 $userlinks,
3464 $revision->getID(),
3465 $tddate,
3466 $tdtime,
3467 $revision->getUser()
3468 ) .
3469 "</div>\n" .
3470 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3471 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3472 $wgOut->setSubtitle( $r );
3473 }
3474
3475 /**
3476 * This function is called right before saving the wikitext,
3477 * so we can do things like signatures and links-in-context.
3478 *
3479 * @param $text String
3480 */
3481 public function preSaveTransform( $text ) {
3482 global $wgParser, $wgUser;
3483 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
3484 }
3485
3486 /* Caching functions */
3487
3488 /**
3489 * checkLastModified returns true if it has taken care of all
3490 * output to the client that is necessary for this request.
3491 * (that is, it has sent a cached version of the page)
3492 */
3493 protected function tryFileCache() {
3494 static $called = false;
3495 if( $called ) {
3496 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3497 return false;
3498 }
3499 $called = true;
3500 if( $this->isFileCacheable() ) {
3501 $cache = new HTMLFileCache( $this->mTitle );
3502 if( $cache->isFileCacheGood( $this->mTouched ) ) {
3503 wfDebug( "Article::tryFileCache(): about to load file\n" );
3504 $cache->loadFromFileCache();
3505 return true;
3506 } else {
3507 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3508 ob_start( array(&$cache, 'saveToFileCache' ) );
3509 }
3510 } else {
3511 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3512 }
3513 return false;
3514 }
3515
3516 /**
3517 * Check if the page can be cached
3518 * @return bool
3519 */
3520 public function isFileCacheable() {
3521 $cacheable = false;
3522 global $wgUseFileCache;
3523 if( $wgUseFileCache and HTMLFileCache::useFileCache() ) {
3524 $cacheable = $this->getID() && !$this->mRedirectedFrom;
3525 // Extension may have reason to disable file caching on some pages.
3526 if( $cacheable ) {
3527 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3528 }
3529 }
3530 return $cacheable;
3531 }
3532
3533 /**
3534 * Loads page_touched and returns a value indicating if it should be used
3535 *
3536 */
3537 public function checkTouched() {
3538 if( !$this->mDataLoaded ) {
3539 $this->loadPageData();
3540 }
3541 return !$this->mIsRedirect;
3542 }
3543
3544 /**
3545 * Get the page_touched field
3546 */
3547 public function getTouched() {
3548 # Ensure that page data has been loaded
3549 if( !$this->mDataLoaded ) {
3550 $this->loadPageData();
3551 }
3552 return $this->mTouched;
3553 }
3554
3555 /**
3556 * Get the page_latest field
3557 */
3558 public function getLatest() {
3559 if( !$this->mDataLoaded ) {
3560 $this->loadPageData();
3561 }
3562 return (int)$this->mLatest;
3563 }
3564
3565 /**
3566 * Edit an article without doing all that other stuff
3567 * The article must already exist; link tables etc
3568 * are not updated, caches are not flushed.
3569 *
3570 * @param $text String: text submitted
3571 * @param $comment String: comment submitted
3572 * @param $minor Boolean: whereas it's a minor modification
3573 */
3574 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3575 wfProfileIn( __METHOD__ );
3576
3577 $dbw = wfGetDB( DB_MASTER );
3578 $revision = new Revision( array(
3579 'page' => $this->getId(),
3580 'text' => $text,
3581 'comment' => $comment,
3582 'minor_edit' => $minor ? 1 : 0,
3583 ) );
3584 $revision->insertOn( $dbw );
3585 $this->updateRevisionOn( $dbw, $revision );
3586
3587 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3588
3589 wfProfileOut( __METHOD__ );
3590 }
3591
3592 /**
3593 * Used to increment the view counter
3594 *
3595 * @param $id Integer: article id
3596 */
3597 public static function incViewCount( $id ) {
3598 $id = intval( $id );
3599 global $wgHitcounterUpdateFreq, $wgDBtype;
3600
3601 $dbw = wfGetDB( DB_MASTER );
3602 $pageTable = $dbw->tableName( 'page' );
3603 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3604 $acchitsTable = $dbw->tableName( 'acchits' );
3605
3606 if( $wgHitcounterUpdateFreq <= 1 ) {
3607 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3608 return;
3609 }
3610
3611 # Not important enough to warrant an error page in case of failure
3612 $oldignore = $dbw->ignoreErrors( true );
3613
3614 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3615
3616 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
3617 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3618 # Most of the time (or on SQL errors), skip row count check
3619 $dbw->ignoreErrors( $oldignore );
3620 return;
3621 }
3622
3623 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3624 $row = $dbw->fetchObject( $res );
3625 $rown = intval( $row->n );
3626 if( $rown >= $wgHitcounterUpdateFreq ){
3627 wfProfileIn( 'Article::incViewCount-collect' );
3628 $old_user_abort = ignore_user_abort( true );
3629
3630 if($wgDBtype == 'mysql')
3631 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3632 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
3633 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3634 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3635 'GROUP BY hc_id');
3636 $dbw->query("DELETE FROM $hitcounterTable");
3637 if($wgDBtype == 'mysql') {
3638 $dbw->query('UNLOCK TABLES');
3639 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3640 'WHERE page_id = hc_id');
3641 }
3642 else {
3643 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3644 "FROM $acchitsTable WHERE page_id = hc_id");
3645 }
3646 $dbw->query("DROP TABLE $acchitsTable");
3647
3648 ignore_user_abort( $old_user_abort );
3649 wfProfileOut( 'Article::incViewCount-collect' );
3650 }
3651 $dbw->ignoreErrors( $oldignore );
3652 }
3653
3654 /**#@+
3655 * The onArticle*() functions are supposed to be a kind of hooks
3656 * which should be called whenever any of the specified actions
3657 * are done.
3658 *
3659 * This is a good place to put code to clear caches, for instance.
3660 *
3661 * This is called on page move and undelete, as well as edit
3662 *
3663 * @param $title a title object
3664 */
3665
3666 public static function onArticleCreate( $title ) {
3667 # Update existence markers on article/talk tabs...
3668 if( $title->isTalkPage() ) {
3669 $other = $title->getSubjectPage();
3670 } else {
3671 $other = $title->getTalkPage();
3672 }
3673 $other->invalidateCache();
3674 $other->purgeSquid();
3675
3676 $title->touchLinks();
3677 $title->purgeSquid();
3678 $title->deleteTitleProtection();
3679 }
3680
3681 public static function onArticleDelete( $title ) {
3682 global $wgMessageCache;
3683 # Update existence markers on article/talk tabs...
3684 if( $title->isTalkPage() ) {
3685 $other = $title->getSubjectPage();
3686 } else {
3687 $other = $title->getTalkPage();
3688 }
3689 $other->invalidateCache();
3690 $other->purgeSquid();
3691
3692 $title->touchLinks();
3693 $title->purgeSquid();
3694
3695 # File cache
3696 HTMLFileCache::clearFileCache( $title );
3697
3698 # Messages
3699 if( $title->getNamespace() == NS_MEDIAWIKI ) {
3700 $wgMessageCache->replace( $title->getDBkey(), false );
3701 }
3702 # Images
3703 if( $title->getNamespace() == NS_FILE ) {
3704 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3705 $update->doUpdate();
3706 }
3707 # User talk pages
3708 if( $title->getNamespace() == NS_USER_TALK ) {
3709 $user = User::newFromName( $title->getText(), false );
3710 $user->setNewtalk( false );
3711 }
3712 # Image redirects
3713 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3714 }
3715
3716 /**
3717 * Purge caches on page update etc
3718 */
3719 public static function onArticleEdit( $title, $flags = '' ) {
3720 global $wgDeferredUpdateList;
3721
3722 // Invalidate caches of articles which include this page
3723 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3724
3725 // Invalidate the caches of all pages which redirect here
3726 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3727
3728 # Purge squid for this page only
3729 $title->purgeSquid();
3730
3731 # Clear file cache for this page only
3732 HTMLFileCache::clearFileCache( $title );
3733 }
3734
3735 /**#@-*/
3736
3737 /**
3738 * Overriden by ImagePage class, only present here to avoid a fatal error
3739 * Called for ?action=revert
3740 */
3741 public function revert() {
3742 global $wgOut;
3743 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3744 }
3745
3746 /**
3747 * Info about this page
3748 * Called for ?action=info when $wgAllowPageInfo is on.
3749 */
3750 public function info() {
3751 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3752
3753 if( !$wgAllowPageInfo ) {
3754 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3755 return;
3756 }
3757
3758 $page = $this->mTitle->getSubjectPage();
3759
3760 $wgOut->setPagetitle( $page->getPrefixedText() );
3761 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3762 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3763
3764 if( !$this->mTitle->exists() ) {
3765 $wgOut->addHTML( '<div class="noarticletext">' );
3766 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3767 // This doesn't quite make sense; the user is asking for
3768 // information about the _page_, not the message... -- RC
3769 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3770 } else {
3771 $msg = $wgUser->isLoggedIn()
3772 ? 'noarticletext'
3773 : 'noarticletextanon';
3774 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3775 }
3776 $wgOut->addHTML( '</div>' );
3777 } else {
3778 $dbr = wfGetDB( DB_SLAVE );
3779 $wl_clause = array(
3780 'wl_title' => $page->getDBkey(),
3781 'wl_namespace' => $page->getNamespace() );
3782 $numwatchers = $dbr->selectField(
3783 'watchlist',
3784 'COUNT(*)',
3785 $wl_clause,
3786 __METHOD__,
3787 $this->getSelectOptions() );
3788
3789 $pageInfo = $this->pageCountInfo( $page );
3790 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3791
3792 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3793 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3794 if( $talkInfo ) {
3795 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3796 }
3797 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3798 if( $talkInfo ) {
3799 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3800 }
3801 $wgOut->addHTML( '</ul>' );
3802 }
3803 }
3804
3805 /**
3806 * Return the total number of edits and number of unique editors
3807 * on a given page. If page does not exist, returns false.
3808 *
3809 * @param $title Title object
3810 * @return array
3811 */
3812 public function pageCountInfo( $title ) {
3813 $id = $title->getArticleId();
3814 if( $id == 0 ) {
3815 return false;
3816 }
3817 $dbr = wfGetDB( DB_SLAVE );
3818 $rev_clause = array( 'rev_page' => $id );
3819 $edits = $dbr->selectField(
3820 'revision',
3821 'COUNT(rev_page)',
3822 $rev_clause,
3823 __METHOD__,
3824 $this->getSelectOptions()
3825 );
3826 $authors = $dbr->selectField(
3827 'revision',
3828 'COUNT(DISTINCT rev_user_text)',
3829 $rev_clause,
3830 __METHOD__,
3831 $this->getSelectOptions()
3832 );
3833 return array( 'edits' => $edits, 'authors' => $authors );
3834 }
3835
3836 /**
3837 * Return a list of templates used by this article.
3838 * Uses the templatelinks table
3839 *
3840 * @return Array of Title objects
3841 */
3842 public function getUsedTemplates() {
3843 $result = array();
3844 $id = $this->mTitle->getArticleID();
3845 if( $id == 0 ) {
3846 return array();
3847 }
3848 $dbr = wfGetDB( DB_SLAVE );
3849 $res = $dbr->select( array( 'templatelinks' ),
3850 array( 'tl_namespace', 'tl_title' ),
3851 array( 'tl_from' => $id ),
3852 __METHOD__ );
3853 if( $res !== false ) {
3854 foreach( $res as $row ) {
3855 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3856 }
3857 }
3858 $dbr->freeResult( $res );
3859 return $result;
3860 }
3861
3862 /**
3863 * Returns a list of hidden categories this page is a member of.
3864 * Uses the page_props and categorylinks tables.
3865 *
3866 * @return Array of Title objects
3867 */
3868 public function getHiddenCategories() {
3869 $result = array();
3870 $id = $this->mTitle->getArticleID();
3871 if( $id == 0 ) {
3872 return array();
3873 }
3874 $dbr = wfGetDB( DB_SLAVE );
3875 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3876 array( 'cl_to' ),
3877 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3878 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3879 __METHOD__ );
3880 if( $res !== false ) {
3881 foreach( $res as $row ) {
3882 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3883 }
3884 }
3885 $dbr->freeResult( $res );
3886 return $result;
3887 }
3888
3889 /**
3890 * Return an applicable autosummary if one exists for the given edit.
3891 * @param $oldtext String: the previous text of the page.
3892 * @param $newtext String: The submitted text of the page.
3893 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3894 * @return string An appropriate autosummary, or an empty string.
3895 */
3896 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3897 # Decide what kind of autosummary is needed.
3898
3899 # Redirect autosummaries
3900 $ot = Title::newFromRedirect( $oldtext );
3901 $rt = Title::newFromRedirect( $newtext );
3902 if( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
3903 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3904 }
3905
3906 # New page autosummaries
3907 if( $flags & EDIT_NEW && strlen( $newtext ) ) {
3908 # If they're making a new article, give its text, truncated, in the summary.
3909 global $wgContLang;
3910 $truncatedtext = $wgContLang->truncate(
3911 str_replace("\n", ' ', $newtext),
3912 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
3913 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3914 }
3915
3916 # Blanking autosummaries
3917 if( $oldtext != '' && $newtext == '' ) {
3918 return wfMsgForContent( 'autosumm-blank' );
3919 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3920 # Removing more than 90% of the article
3921 global $wgContLang;
3922 $truncatedtext = $wgContLang->truncate(
3923 $newtext,
3924 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
3925 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3926 }
3927
3928 # If we reach this point, there's no applicable autosummary for our case, so our
3929 # autosummary is empty.
3930 return '';
3931 }
3932
3933 /**
3934 * Add the primary page-view wikitext to the output buffer
3935 * Saves the text into the parser cache if possible.
3936 * Updates templatelinks if it is out of date.
3937 *
3938 * @param $text String
3939 * @param $cache Boolean
3940 */
3941 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
3942 global $wgOut;
3943
3944 $this->mParserOutput = $this->getOutputFromWikitext( $text, $cache, $parserOptions );
3945 $wgOut->addParserOutput( $this->mParserOutput );
3946 }
3947
3948 /**
3949 * This does all the heavy lifting for outputWikitext, except it returns the parser
3950 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
3951 * say, embedding thread pages within a discussion system (LiquidThreads)
3952 */
3953 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
3954 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3955
3956 if ( !$parserOptions ) {
3957 $parserOptions = $this->getParserOptions();
3958 }
3959
3960 $time = -wfTime();
3961 $this->mParserOutput = $wgParser->parse( $text, $this->mTitle,
3962 $parserOptions, true, true, $this->getRevIdFetched() );
3963 $time += wfTime();
3964
3965 # Timing hack
3966 if( $time > 3 ) {
3967 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3968 $this->mTitle->getPrefixedDBkey()));
3969 }
3970
3971 if( $wgEnableParserCache && $cache && $this && $this->mParserOutput->getCacheTime() != -1 ) {
3972 $parserCache = ParserCache::singleton();
3973 $parserCache->save( $this->mParserOutput, $this, $parserOptions );
3974 }
3975 // Make sure file cache is not used on uncacheable content.
3976 // Output that has magic words in it can still use the parser cache
3977 // (if enabled), though it will generally expire sooner.
3978 if( $this->mParserOutput->getCacheTime() == -1 || $this->mParserOutput->containsOldMagic() ) {
3979 $wgUseFileCache = false;
3980 }
3981 $this->doCascadeProtectionUpdates( $this->mParserOutput );
3982 return $this->mParserOutput;
3983 }
3984
3985 /**
3986 * Get parser options suitable for rendering the primary article wikitext
3987 */
3988 public function getParserOptions() {
3989 global $wgUser;
3990 if ( !$this->mParserOptions ) {
3991 $this->mParserOptions = new ParserOptions( $wgUser );
3992 $this->mParserOptions->setTidy( true );
3993 $this->mParserOptions->enableLimitReport();
3994 }
3995 return $this->mParserOptions;
3996 }
3997
3998 protected function doCascadeProtectionUpdates( $parserOutput ) {
3999 if( !$this->isCurrent() || wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
4000 return;
4001 }
4002
4003 // templatelinks table may have become out of sync,
4004 // especially if using variable-based transclusions.
4005 // For paranoia, check if things have changed and if
4006 // so apply updates to the database. This will ensure
4007 // that cascaded protections apply as soon as the changes
4008 // are visible.
4009
4010 # Get templates from templatelinks
4011 $id = $this->mTitle->getArticleID();
4012
4013 $tlTemplates = array();
4014
4015 $dbr = wfGetDB( DB_SLAVE );
4016 $res = $dbr->select( array( 'templatelinks' ),
4017 array( 'tl_namespace', 'tl_title' ),
4018 array( 'tl_from' => $id ),
4019 __METHOD__ );
4020
4021 global $wgContLang;
4022 foreach( $res as $row ) {
4023 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4024 }
4025
4026 # Get templates from parser output.
4027 $poTemplates = array();
4028 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4029 foreach ( $templates as $dbk => $id ) {
4030 $poTemplates["$ns:$dbk"] = true;
4031 }
4032 }
4033
4034 # Get the diff
4035 # Note that we simulate array_diff_key in PHP <5.0.x
4036 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4037
4038 if( count( $templates_diff ) > 0 ) {
4039 # Whee, link updates time.
4040 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
4041 $u->doUpdate();
4042 }
4043 }
4044
4045 /**
4046 * Update all the appropriate counts in the category table, given that
4047 * we've added the categories $added and deleted the categories $deleted.
4048 *
4049 * @param $added array The names of categories that were added
4050 * @param $deleted array The names of categories that were deleted
4051 * @return null
4052 */
4053 public function updateCategoryCounts( $added, $deleted ) {
4054 $ns = $this->mTitle->getNamespace();
4055 $dbw = wfGetDB( DB_MASTER );
4056
4057 # First make sure the rows exist. If one of the "deleted" ones didn't
4058 # exist, we might legitimately not create it, but it's simpler to just
4059 # create it and then give it a negative value, since the value is bogus
4060 # anyway.
4061 #
4062 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4063 $insertCats = array_merge( $added, $deleted );
4064 if( !$insertCats ) {
4065 # Okay, nothing to do
4066 return;
4067 }
4068 $insertRows = array();
4069 foreach( $insertCats as $cat ) {
4070 $insertRows[] = array( 'cat_title' => $cat );
4071 }
4072 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
4073
4074 $addFields = array( 'cat_pages = cat_pages + 1' );
4075 $removeFields = array( 'cat_pages = cat_pages - 1' );
4076 if( $ns == NS_CATEGORY ) {
4077 $addFields[] = 'cat_subcats = cat_subcats + 1';
4078 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4079 } elseif( $ns == NS_FILE ) {
4080 $addFields[] = 'cat_files = cat_files + 1';
4081 $removeFields[] = 'cat_files = cat_files - 1';
4082 }
4083
4084 if( $added ) {
4085 $dbw->update(
4086 'category',
4087 $addFields,
4088 array( 'cat_title' => $added ),
4089 __METHOD__
4090 );
4091 }
4092 if( $deleted ) {
4093 $dbw->update(
4094 'category',
4095 $removeFields,
4096 array( 'cat_title' => $deleted ),
4097 __METHOD__
4098 );
4099 }
4100 }
4101
4102 /** Lightweight method to get the parser output for a page, checking the parser cache
4103 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4104 * consider, so it's not appropriate to use there. */
4105 function getParserOutput( $oldid = null ) {
4106 global $wgEnableParserCache, $wgUser, $wgOut;
4107
4108 // Should the parser cache be used?
4109 $useParserCache = $wgEnableParserCache &&
4110 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
4111 $this->exists() &&
4112 $oldid === null;
4113
4114 wfDebug( __METHOD__.': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
4115 if ( $wgUser->getOption( 'stubthreshold' ) ) {
4116 wfIncrStats( 'pcache_miss_stub' );
4117 }
4118
4119 $parserOutput = false;
4120 if ( $useParserCache ) {
4121 $parserOutput = ParserCache::singleton()->get( $this, $this->getParserOptions() );
4122 }
4123
4124 if ( $parserOutput === false ) {
4125 // Cache miss; parse and output it.
4126 $rev = Revision::newFromTitle( $this->getTitle(), $oldid );
4127
4128 return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4129 } else {
4130 return $parserOutput;
4131 }
4132 }
4133 }